Compare commits

...

229 Commits

Author SHA1 Message Date
Sebastian McKenzie
750ec7783f v2.12.5 2015-01-16 08:08:52 +11:00
Sebastian McKenzie
14ae438735 remove declarators push in let scoping 2015-01-16 08:06:38 +11:00
Sebastian McKenzie
2f8bdd7e27 add 2.12.5 changelog 2015-01-16 07:59:40 +11:00
Sebastian McKenzie
87da9fcfc5 fix let scoping for loop - closes #509 2015-01-16 07:58:14 +11:00
Sebastian McKenzie
51f6cfddca remove instanbul inclusion 2015-01-16 02:47:20 +11:00
Sebastian McKenzie
b9ad4c2773 v2.12.4 2015-01-16 02:41:23 +11:00
Sebastian McKenzie
228b3dbc34 fix linting errors 2015-01-16 02:38:45 +11:00
Sebastian McKenzie
a01802300f fix default parameters transformer for loops 2015-01-16 02:36:56 +11:00
Sebastian McKenzie
51c6a3fffc fix let scoping body not existing 2015-01-16 02:31:36 +11:00
Sebastian McKenzie
4668e1d67b fix linting errors 2015-01-16 02:29:35 +11:00
Sebastian McKenzie
75e9097e19 add 2.12.4 changelog 2015-01-16 02:29:02 +11:00
Sebastian McKenzie
0627cd94d4 turn array for ins into fors 2015-01-16 02:25:41 +11:00
Sebastian McKenzie
71879d6e8f Merge branch 'master' of github.com:6to5/6to5 2015-01-16 00:50:55 +11:00
Sebastian McKenzie
d7810cac08 add ambiguous rest parameters comment 2015-01-16 00:50:38 +11:00
Sebastian McKenzie
dc9efd21d3 Merge pull request #507 from leebyron/unused
Rm unused dependencies (pass lint)
2015-01-16 00:47:55 +11:00
Lee Byron
347e490614 Rm unused dependencies (pass lint) 2015-01-15 08:47:03 -05:00
Sebastian McKenzie
e512264be7 Merge pull request #506 from leebyron/rest
Improve performance of rest parameter.
2015-01-16 00:43:56 +11:00
Lee Byron
9624663e60 Improve performance of rest parameter.
Rather than initing an empty array and filling, create an array of the correct size up-front. Minor gain on chromium, but considerably (~5x) faster in spidermonkey/firefox.
2015-01-15 08:41:53 -05:00
Sebastian McKenzie
3cf8a6df01 rename replaceInstanceSuperReferences to replaceSuperReferences in classes transformer and add breaks on method definitions 2015-01-15 23:08:28 +11:00
Sebastian McKenzie
88eacecd72 clarify traceur ignore tests 2015-01-15 23:08:06 +11:00
Sebastian McKenzie
fcd3c9ce65 remove register blacklist tests 2015-01-15 23:07:52 +11:00
Sebastian McKenzie
1733bac3bb move chokidar to top 2015-01-15 23:07:46 +11:00
Sebastian McKenzie
21cd063274 Merge pull request #503 from shinnn/output-file-sync
Use output-file-sync instead of mkdirp
2015-01-15 20:32:48 +11:00
Shinnosuke Watanabe
db5750643a use output-file-sync instead of mkdirp
https://github.com/shinnn/output-file-sync
2015-01-15 18:29:40 +09:00
Sebastian McKenzie
60dae7a88d add build comprehension helper 2015-01-15 20:13:24 +11:00
Sebastian McKenzie
790c924b54 abstract out build comprehension helper 2015-01-15 20:13:16 +11:00
Sebastian McKenzie
50d7a46c7f abstract away remap async to generator helper 2015-01-15 20:09:50 +11:00
Sebastian McKenzie
6f7da38957 abstract out named method helper 2015-01-15 20:07:32 +11:00
Sebastian McKenzie
80764c214a add rest parameter comments 2015-01-15 19:52:53 +11:00
Sebastian McKenzie
55054e45da Revert "Improve performance of rest parameter."
This reverts commit e5463cc2a9.
2015-01-15 19:34:33 +11:00
Sebastian McKenzie
060aa5ba0b fix rest parameter check in types.isReferenced 2015-01-15 19:29:54 +11:00
Sebastian McKenzie
688d619bfe add identifier check to class id inheritance 2015-01-15 19:29:54 +11:00
Sebastian McKenzie
6db7fce543 fix computed member expressions in playground memoization 2015-01-15 19:29:54 +11:00
Sebastian McKenzie
41ff1d4ace upgrade acorn-6to5 2015-01-15 19:29:54 +11:00
Sebastian McKenzie
1c6eeba2e9 Merge pull request #499 from leebyron/rest
Improve performance of rest parameter.
2015-01-15 19:28:32 +11:00
Sebastian McKenzie
488b719fde Merge pull request #494 from gaearon/perf-2
Performance impovements
2015-01-15 19:28:04 +11:00
Sebastian McKenzie
af32080287 Merge pull request #498 from leebyron/patch-1
Update CONTRIBUTING.md
2015-01-15 19:27:07 +11:00
Sebastian McKenzie
4c1cd13536 Merge pull request #501 from shinnn/package-json
Update repository info and homepage URL
2015-01-15 14:36:39 +11:00
Dan Abramov
1002cf7796 Avoid Node allocations by making prototype call statics 2015-01-15 04:18:18 +03:00
Shinnosuke Watanabe
081dd33e73 Update repository info and homepage URL
* link to https://6to5.org
* use user/repo style
2015-01-15 10:07:54 +09:00
Sebastian McKenzie
bd9dc4f15d Merge pull request #500 from shinnn/container-based-build
Use container-based infrastructure on Travis CI
2015-01-15 12:01:33 +11:00
Shinnosuke Watanabe
c7ba566ad6 Use container-based infrastructure on Travis CI
http://docs.travis-ci.com/user/workers/container-based-infrastructure/
2015-01-15 09:55:10 +09:00
Dan Abramov
a1b326a0ab Use object lookup instead of array 2015-01-15 03:51:22 +03:00
Dan Abramov
a452f781b8 Slightly refactor and add explanations for optimized functions 2015-01-15 03:39:24 +03:00
Lee Byron
e5463cc2a9 Improve performance of rest parameter.
Rather than initing an empty array and filling, create an array of the correct size up-front. Minor gain on chromium, but considerably (~5x) faster in spidermonkey/firefox.
2015-01-14 19:08:14 -05:00
Lee Byron
7d732ef503 Update CONTRIBUTING.md 2015-01-14 19:01:53 -05:00
Lee Byron
25cb0c6344 Update CONTRIBUTING.md
Explain git init submodules step when checking out
2015-01-14 18:23:49 -05:00
Sebastian McKenzie
45a52bf478 Merge pull request #496 from swirlycheetah/master
Expand upon the contributing guidelines
2015-01-15 09:41:12 +11:00
Chris Wheatley
a14f971b8a add further commands required for workflow 2015-01-14 22:25:20 +00:00
Chris Wheatley
da65500545 expand upon the contributing guidelines 2015-01-14 22:11:46 +00:00
Dan Abramov
58a91ee9e9 Optimize node type lookup 2015-01-14 23:01:58 +03:00
Dan Abramov
19eaa181a5 Speed up common case where consumer moves only forward 2015-01-14 20:02:40 +03:00
Dan Abramov
c7c90acf3f Store ranges instead of line indexes for performance 2015-01-14 19:14:47 +03:00
Dan Abramov
c6f3a55c03 Refactor buffer for clarity and avoid regex for performance 2015-01-14 19:14:47 +03:00
Sebastian McKenzie
e01b7d288f v2.12.3 2015-01-15 02:29:44 +11:00
Sebastian McKenzie
98c0e185b8 add missing semicolon 2015-01-15 02:27:45 +11:00
Sebastian McKenzie
bf66d78210 add 2.12.3 changelog 2015-01-15 02:27:17 +11:00
Sebastian McKenzie
b60eca0a76 better typeof symbol transformer 2015-01-15 02:24:32 +11:00
Sebastian McKenzie
44f06c0b4c instance and static class method names 2015-01-15 02:24:23 +11:00
Sebastian McKenzie
6c5606b7e8 call transformer methods on traverse context 2015-01-15 02:24:05 +11:00
Sebastian McKenzie
07ddfbeb5d remove pointless prototypeProperties helper call 2015-01-15 01:20:06 +11:00
Sebastian McKenzie
87b890c172 fix parentheses deletion not support multilines - fixes #490 2015-01-15 01:14:49 +11:00
Sebastian McKenzie
245fcfe110 move mutator map checking to after loose test 2015-01-15 01:09:13 +11:00
Sebastian McKenzie
4744719040 v2.12.2 2015-01-14 18:48:29 +11:00
Sebastian McKenzie
a3b814a897 fix default parameters closure scope 2015-01-14 18:46:36 +11:00
Sebastian McKenzie
f5f17f0ccb ignore function params, rest and catch clauses - webpack/webpack#688 2015-01-14 18:39:07 +11:00
Sebastian McKenzie
f6a2acdfb1 v2.12.1 2015-01-14 18:06:51 +11:00
Sebastian McKenzie
e8dba2ad1e add 2.12.1 changelog 2015-01-14 18:05:11 +11:00
Sebastian McKenzie
8ce5c5b608 add jsx to possible extensions 2015-01-14 18:04:14 +11:00
Sebastian McKenzie
0dfea1a51b update notes 2015-01-14 14:54:31 +11:00
Sebastian McKenzie
a4e528e2b3 v2.12.0 2015-01-14 10:14:14 +11:00
Sebastian McKenzie
99ca9b7e9a fix linting errors 2015-01-14 10:12:11 +11:00
Sebastian McKenzie
313e932e7c fix linting errors 2015-01-14 10:11:41 +11:00
Sebastian McKenzie
6a57a4e565 fix linting errors 2015-01-14 10:11:07 +11:00
Sebastian McKenzie
fc3a5f25fb add 2.12.0 changelog 2015-01-14 10:09:47 +11:00
Sebastian McKenzie
e258b85420 clean up loose template literals 2015-01-14 08:55:24 +11:00
Sebastian McKenzie
6b836de306 add #480 test 2015-01-14 07:56:45 +11:00
Sebastian McKenzie
fe6f53d471 Merge pull request #480 from monsanto/loose-templates
Add loose transform for tagged template literals
2015-01-14 07:54:19 +11:00
Sebastian McKenzie
3b259c6b1e clean up 6to5 register-browser 2015-01-14 07:31:51 +11:00
Sebastian McKenzie
2005df3fa2 support non-string jsx literals - fixes #479 2015-01-14 07:31:28 +11:00
Christopher Monsanto
4fdcf685d3 add loose transform for tagged template literals 2015-01-13 14:48:31 -05:00
Sebastian McKenzie
afd3af834d add loose option to computed property names 2015-01-14 00:35:45 +11:00
Sebastian McKenzie
8afec8b12a rename fast mode to loose #465 2015-01-14 00:24:34 +11:00
Sebastian McKenzie
f25ed0b5de add minimum of 1 newline after line comments - fixes #442 and fixes #477 2015-01-13 23:27:52 +11:00
Sebastian McKenzie
4898770d60 ignore test262 in istanbul 2015-01-13 23:27:26 +11:00
Sebastian McKenzie
bd2fa77446 fix fast forOf and add tests 2015-01-13 23:18:46 +11:00
Sebastian McKenzie
1c2bafe0e1 use assignment instead of define for fast classes 2015-01-13 23:18:38 +11:00
Sebastian McKenzie
f8915333b0 remove double spaces in version read in makefile 2015-01-13 22:44:26 +11:00
Sebastian McKenzie
f8275adc6f upgrade acorn-6to5 2015-01-13 22:44:06 +11:00
Sebastian McKenzie
2a97a4233d remove invalid jshint options 2015-01-13 22:26:33 +11:00
Sebastian McKenzie
70eae9f6ce remove functions inside of loops 2015-01-13 22:18:58 +11:00
Sebastian McKenzie
f560062d82 remove loopfunc: false from jshint - thanks @dcousens... 2015-01-13 22:02:30 +11:00
Sebastian McKenzie
0f55a66f5b add "fast" option for transformers 2015-01-13 22:02:04 +11:00
Sebastian McKenzie
f14f72b635 add --mangle option to uglify 2015-01-13 22:01:37 +11:00
Sebastian McKenzie
9aa010d987 v2.11.4 2015-01-13 20:15:35 +11:00
Sebastian McKenzie
bd179ace86 add 2.11.4 changelog 2015-01-13 20:08:38 +11:00
Sebastian McKenzie
4df6d6043e make dependency versions static - fixes #475 2015-01-13 20:07:34 +11:00
Sebastian McKenzie
7ed7475c46 v2.11.3 2015-01-13 14:35:14 +11:00
Sebastian McKenzie
b2dc560a2d allow a string to be passed as the optional option 2015-01-13 14:33:18 +11:00
Sebastian McKenzie
010dbe1cce v2.11.2 2015-01-13 11:29:46 +11:00
Sebastian McKenzie
75cd0bab02 add 2.11.2 changelog 2015-01-13 11:26:07 +11:00
Sebastian McKenzie
3283991ed0 flip es6 geneartors include regenerator tests 2015-01-13 10:56:36 +11:00
Sebastian McKenzie
a66ce5b6ce add ignore ast check to es6 generators test because regenerator outputs an invalid ast 2015-01-13 10:44:17 +11:00
Sebastian McKenzie
9620f50f22 fix #474 test 2015-01-13 10:32:39 +11:00
Sebastian McKenzie
cc049ea851 Merge pull request #474 from amasad/master
Handle esprima-like AST catch clause in a TryStatement. Fixes #473
2015-01-13 10:26:47 +11:00
Amjad Masad
e5a04ae117 Add test 2015-01-12 17:56:16 -05:00
Amjad Masad
e07e74f010 Handle esprima-like AST catch clause in a TryStatement. Fixes #473 2015-01-12 17:32:02 -05:00
Sebastian McKenzie
7b04c501eb fix formatting of #472 2015-01-13 08:54:43 +11:00
Sebastian McKenzie
70349dd4b3 Merge pull request #472 from monsanto/no-traceback-on-syntax-err
don't print traceback on syntax error in CLI
2015-01-13 08:52:42 +11:00
Christopher Monsanto
2cedc843a8 don't print traceback on syntax error in CLI 2015-01-12 16:49:28 -05:00
Sebastian McKenzie
cf40fe3430 v2.11.1 2015-01-13 08:21:54 +11:00
Sebastian McKenzie
09ffeed139 add 2.11.1 changelog 2015-01-13 08:19:33 +11:00
Sebastian McKenzie
18f79d6253 Merge pull request #470 from monsanto/fix-dict-aliasing
remove Dict from core aliasable constructors
2015-01-13 08:17:23 +11:00
Christopher Monsanto
6f5270f38f remove Dict from core aliasable constructors 2015-01-12 14:00:43 -05:00
Brian Donovan
aac7aac373 Merge pull request #469 from clavery/master
remove console.log from react transforms
2015-01-12 10:29:29 -08:00
Charles Lavery
9361470dc7 remove console.log from react transforms 2015-01-12 13:19:32 -05:00
Sebastian McKenzie
cf579f4b6e v2.11.0 2015-01-13 01:53:03 +11:00
Sebastian McKenzie
2e497eef98 fix linting errors 2015-01-13 01:51:21 +11:00
Sebastian McKenzie
7867daaa04 add 2.11.0 changelog 2015-01-13 01:50:30 +11:00
Sebastian McKenzie
eabbcd31ad add comments to ambiguous code 2015-01-13 01:50:30 +11:00
Sebastian McKenzie
17d198f3d6 Merge pull request #468 from AluisioASG/core-aliasable
Whitelist constructors aliasable to core-js
2015-01-13 01:46:19 +11:00
Aluísio Augusto Silva Gonçalves
afd5376c8d Whitelist constructors aliasable to core-js
Expand the list of identifiers for which we substitute `_core.<Something>`
for `<Something>`.  Also an alternative fix for #421.
2015-01-12 12:29:37 -02:00
Sebastian McKenzie
02a50c9f7e fix unnecessary default parameter iife - fixes #251 2015-01-13 01:16:00 +11:00
Sebastian McKenzie
df9fa32b82 add optional to keep module id extensions - fixes #420 2015-01-13 01:12:14 +11:00
Sebastian McKenzie
831b420df3 special case single super method call with spread, fixes #227 2015-01-13 01:09:10 +11:00
Sebastian McKenzie
123186003c add support for super instead of closures - fixes #425 2015-01-13 01:00:35 +11:00
Sebastian McKenzie
ea627ed57c don't use function variable declaration for class constructor 2015-01-13 00:03:52 +11:00
Sebastian McKenzie
157bb48776 add 3.0.0 fast transformer note 2015-01-12 23:27:04 +11:00
Sebastian McKenzie
76a3771943 change ambiguous _inherits parameters 2015-01-12 20:54:37 +11:00
Sebastian McKenzie
54f8889a30 v2.10.1 2015-01-12 20:09:54 +11:00
Sebastian McKenzie
bab159bc08 fix version number in changelog 2015-01-12 20:08:14 +11:00
Sebastian McKenzie
23950963e5 add upgrade core-js note 2015-01-12 20:07:51 +11:00
Sebastian McKenzie
d1daac5550 add global shim due to core-js 0.4.4 2015-01-12 20:07:30 +11:00
Sebastian McKenzie
d93ece5ccf add 2.10.11 changelog 2015-01-12 20:05:19 +11:00
Sebastian McKenzie
c8c667bf16 add back loop ensure block 2015-01-12 20:04:19 +11:00
Sebastian McKenzie
49cdacbcb4 add includeRegenerator option 2015-01-12 20:03:02 +11:00
Sebastian McKenzie
f97bd584f7 upgrade core-js 2015-01-12 19:49:04 +11:00
Sebastian McKenzie
f1328aa82f v2.10.0 2015-01-12 11:52:32 +11:00
Sebastian McKenzie
e298a5d350 remove unused check function 2015-01-12 11:50:45 +11:00
Sebastian McKenzie
89a6ef0b26 add 2.10.0 changelog 2015-01-12 11:50:19 +11:00
Sebastian McKenzie
c7ac9b7815 rename --reactCompat arg to --react-compat 2015-01-12 11:47:04 +11:00
Sebastian McKenzie
55c99b9122 upgrade acorn-6to5 2015-01-12 11:45:21 +11:00
Sebastian McKenzie
545c8c3adb define class methods instead of assigning them - fixes #454 2015-01-12 11:44:23 +11:00
Sebastian McKenzie
d093dc8231 disallow setters without one parameter - fixes #455 2015-01-12 10:25:37 +11:00
Sebastian McKenzie
eaf9d58b8d Merge branch 'master' of github.com:6to5/6to5 2015-01-12 10:19:53 +11:00
Sebastian McKenzie
6131cea5b2 add classesFastSuper optional transformer - fixes #451 2015-01-12 10:19:22 +11:00
Sebastian McKenzie
ca4831febe Merge pull request #453 from amasad/master
Add --reactCompat option to cli
2015-01-12 09:57:21 +11:00
Amjad Masad
9cf8d05a19 Add --reactCompat option to cli 2015-01-11 12:47:17 -05:00
Sebastian McKenzie
2a4f03330b better bin name for 6to5-node 2015-01-11 22:59:36 +11:00
Sebastian McKenzie
83bc614bad add note about splitting up super transforming #411 2015-01-11 22:42:45 +11:00
Sebastian McKenzie
99ccb4111a start adding support for this mapping for supers 2015-01-11 22:15:56 +11:00
Sebastian McKenzie
f6c72e9ae9 add newline to scope 2015-01-11 22:15:56 +11:00
Sebastian McKenzie
a90730d4bf Merge pull request #449 from monsanto/fix-6to5-node-name
fix _6to5-node name in help screen
2015-01-11 18:19:04 +11:00
Christopher Monsanto
29503d2d37 fix _6to5-node name in help screen 2015-01-10 23:04:13 -05:00
Sebastian McKenzie
35451ed408 Merge pull request #447 from fkling/cli
Fix short --whitelist option
2015-01-11 11:21:41 +11:00
Felix Kling
7167aeb65a Fix short --whitelist option
`6to5 -w generators` doesn't work because `-w` is also short for
`--watch`. This changes the short option for `--whitelist` to `-l`.
2015-01-10 11:03:26 -08:00
Sebastian McKenzie
29d0489443 add autoindentation note 2015-01-11 04:55:34 +11:00
Sebastian McKenzie
82aa2686f9 fix writable being set on accessors 2015-01-11 04:55:27 +11:00
Sebastian McKenzie
24616fa08a fix linting errors 2015-01-11 03:35:37 +11:00
Sebastian McKenzie
9f3e1eabfd simplify define properties 2015-01-11 03:21:05 +11:00
Sebastian McKenzie
286d2f84bd add configurable and writable property to defined properties 2015-01-11 02:43:17 +11:00
Sebastian McKenzie
7fc484d82e add ES5 getter/setter split up note - closes #444 2015-01-11 02:30:11 +11:00
Sebastian McKenzie
ad6ab57fe3 only use raw type references in coreAliasing on Symbol - fixes #421 2015-01-11 01:00:04 +11:00
Sebastian McKenzie
348fe045d3 reformat for of transformers and add pattern support 2015-01-11 00:35:41 +11:00
Sebastian McKenzie
980b20316b Merge pull request #441 from monsanto/fast-for-of
Optional for-of transformer that puts arrays in fast path
2015-01-11 00:32:56 +11:00
Sebastian McKenzie
5b52e507ca fix non-identifier class super tests 2015-01-10 22:55:19 +11:00
Sebastian McKenzie
9853c9d78d add empty statement case to toBlock 2015-01-10 22:42:35 +11:00
Sebastian McKenzie
72ec771725 fix unnecessarily shifting super ref 2015-01-10 22:42:20 +11:00
Sebastian McKenzie
75e97d9f7e format scope default declarations better 2015-01-10 22:34:08 +11:00
Sebastian McKenzie
295faf185c remove unnecessary ensureBlock in let scoping transformer #434 2015-01-10 22:33:57 +11:00
Sebastian McKenzie
54b05f33f2 move super reference into closure 2015-01-10 22:26:51 +11:00
Sebastian McKenzie
1985146760 use Array.isArray instead of _.isArray 2015-01-10 22:26:37 +11:00
Sebastian McKenzie
13a52dd300 always use an IIFE for classes - fixes #435 2015-01-10 22:18:30 +11:00
Sebastian McKenzie
9d4bea70e6 Merge pull request #433 from gaearon/perf-traverse-refactor
Refactor traversal to avoid closures for perf
2015-01-10 22:06:08 +11:00
Dan Abramov
421906bcc1 Refactor traversal to avoid closures 2015-01-10 14:02:08 +03:00
Sebastian McKenzie
508b3531e5 Merge pull request #432 from gaearon/perf-stable
Replace _.each and for-in with for loop in hot paths
2015-01-10 21:49:37 +11:00
Sebastian McKenzie
c67c407cd0 v2.9.4 2015-01-10 16:28:02 +11:00
Sebastian McKenzie
aa552fea0d add 2.9.4 changelog 2015-01-10 16:25:39 +11:00
Sebastian McKenzie
9bbf109dc8 support UpdateExpressions as MemberExpression objects - fixes #440 2015-01-10 16:24:17 +11:00
Christopher Monsanto
393d52088a optional for-of transformer that puts arrays in fast path 2015-01-09 20:53:48 -05:00
Dan Abramov
5783973734 A few minor perf improvements 2015-01-09 22:00:07 +03:00
Dan Abramov
55e01afd0d Improve performance on hot paths by using for loops 2015-01-09 16:51:34 +03:00
Dan Abramov
1231dc6cef Replace _.each and for-in with for loop in hot paths 2015-01-09 16:00:53 +03:00
Sebastian McKenzie
b08f2061b5 fix destructuring tests 2015-01-09 21:43:24 +11:00
Sebastian McKenzie
1536d3de91 Revert "add base optional object observe transformer"
This reverts commit b619e843a9.
2015-01-09 21:18:55 +11:00
Sebastian McKenzie
fddacb1612 don't assign array expressions to a temp variable in destructuring #431 2015-01-09 21:18:51 +11:00
Sebastian McKenzie
9d1ff2b71b v2.9.3 2015-01-09 20:10:17 +11:00
Sebastian McKenzie
1c8d24f78c remove exportsWildcard helper in favor of defaults #430 2015-01-09 20:08:05 +11:00
Sebastian McKenzie
b619e843a9 add base optional object observe transformer 2015-01-09 19:57:21 +11:00
Sebastian McKenzie
e6a71c5849 move npm version up 2015-01-09 19:56:22 +11:00
Sebastian McKenzie
682668c219 v2.9.2 2015-01-09 19:51:44 +11:00
Sebastian McKenzie
dd64297838 add 2.9.2 changelog 2015-01-09 19:49:10 +11:00
Sebastian McKenzie
944a9d3908 pass exports to exportsWildcard - fixes #430 2015-01-09 19:48:11 +11:00
Sebastian McKenzie
d6922c9b75 v2.9.1 2015-01-09 19:34:28 +11:00
Sebastian McKenzie
fb0fcc7138 fix runtime generator breaking the helper inclusion loop - fixes #429 2015-01-09 19:31:43 +11:00
Sebastian McKenzie
89148e6029 Merge pull request #424 from 6to5/more-super-issues
Ensure more than one level of superclass works.
2015-01-09 08:35:40 +11:00
Brian Donovan
28d10b8eb4 Ensure more than one level of superclass works. 2015-01-08 13:33:02 -08:00
Sebastian McKenzie
3509990563 enable esnext tests by default 2015-01-09 07:23:17 +11:00
Sebastian McKenzie
c5960fb9f7 Merge pull request #408 from 6to5/fix-esnext-class-tests
[WIP] Fix super with getters and setters and with class prototypes changing.
2015-01-09 07:22:35 +11:00
Brian Donovan
07131576cf Use undefined instead of void 0. 2015-01-08 11:59:01 -08:00
Sebastian McKenzie
e75e778300 v2.9.0 2015-01-09 06:02:43 +11:00
Sebastian McKenzie
f6cb14c975 upgrade acorn-6to5 2015-01-09 06:00:19 +11:00
Brian Donovan
af1912ab7a Ensure constructors use the current super class.
This is an extension of 324a4a1b22.
2015-01-08 09:31:18 -08:00
Brian Donovan
8c478f29bc Use desc.writable instead of "writable" in desc as suggested by @stefanpenner. 2015-01-08 09:21:35 -08:00
Brian Donovan
5b4d6d7ba9 Replace superIdentifier with superProperty.
This also disallows the usage of bare `super` that is not part of a
member expression, call expression, or new expression.
2015-01-08 09:21:32 -08:00
Sebastian McKenzie
1776b072b0 v2.8.2 2015-01-09 00:08:42 +11:00
Sebastian McKenzie
726fad1b6c move publish-core into publish task 2015-01-09 00:06:21 +11:00
Sebastian McKenzie
23c16b0094 fix github url in no templates directory 2015-01-09 00:06:12 +11:00
Sebastian McKenzie
24f70ee4d0 add alternate core package - fixes #387 2015-01-08 23:31:03 +11:00
Sebastian McKenzie
fe9b0afd95 v2.8.1 2015-01-08 23:14:56 +11:00
Sebastian McKenzie
47695a8710 add 2.8.1 changelog 2015-01-08 23:12:36 +11:00
Sebastian McKenzie
e1c7584280 fix computed accessors on objects 2015-01-08 23:11:58 +11:00
Sebastian McKenzie
3e63e6cd4b v2.8.0 2015-01-08 22:49:23 +11:00
Sebastian McKenzie
ba643680e5 add 2.8.0 changelog 2015-01-08 22:46:16 +11:00
Sebastian McKenzie
611137c7d7 add umd strict and amd strict module formatter, also fix bug with wrong amd module constructor - fixes #415 2015-01-08 22:44:51 +11:00
Sebastian McKenzie
6240e5111f add modules common strict formatter - fixes #418 2015-01-08 22:29:24 +11:00
Brian Donovan
324a4a1b22 Fix super with getters and setters and with class prototypes changing. 2015-01-07 21:10:36 -08:00
Sebastian McKenzie
035f667a8f update notes with additional 3.0.0 breaking change and add a reference to the export default issue 2015-01-08 13:09:59 +11:00
Sebastian McKenzie
98985dd253 Merge pull request #416 from monsanto/indent
Add --indent option to change indent width
2015-01-08 12:43:41 +11:00
Christopher Monsanto
0a207903ce Add --indent option to change indent width 2015-01-07 18:27:58 -05:00
Sebastian McKenzie
90437d262b v2.7.4 2015-01-08 01:02:39 +11:00
Sebastian McKenzie
4aba7ec192 fix generation tests and add variable kind length 2015-01-08 01:00:32 +11:00
Sebastian McKenzie
a924c9c218 fix up declarations being split up and use a new algorithm to determine whether or not we should align them 2015-01-08 00:54:01 +11:00
Sebastian McKenzie
a2ed0ea9c5 only align variable declarations if at least one declarator has an init 2015-01-08 00:44:53 +11:00
Sebastian McKenzie
c5cd729c3d add 2.7.4 changelog 2015-01-08 00:40:43 +11:00
Sebastian McKenzie
b065d43a6d add custom level to buffer getIndent 2015-01-08 00:37:46 +11:00
Sebastian McKenzie
281003c7bd properly align multi declarator var declarations - fixes #413 2015-01-08 00:37:32 +11:00
Sebastian McKenzie
6650336c64 inherit assign from declaration in destructuring - fixes #413 2015-01-08 00:37:07 +11:00
Sebastian McKenzie
f904734695 rename prettyPrint to the more descriptive prettyCall 2015-01-08 00:36:40 +11:00
298 changed files with 3879 additions and 1118 deletions

1
.gitignore vendored
View File

@@ -10,3 +10,4 @@ test/tmp
/runtime.js
coverage
dist
.package.json

View File

@@ -5,7 +5,6 @@
"camelcase": true,
"unused": true,
"eqnull": true,
"proto": true,
"newcap": true,
"supernew": true,
"noyield": true,
@@ -14,8 +13,6 @@
"boss": true,
"expr": true,
"undef": true,
"loopfunc": true,
"white": true,
"maxparams": 5,
"maxdepth": 4,

View File

@@ -9,3 +9,4 @@ Makefile
dist
tests.json
CHANGELOG.md
.package.json

View File

@@ -1,3 +1,4 @@
sudo: false
language: node_js
node_js:
- "0.10"

View File

@@ -11,6 +11,146 @@
_Note: Gaps between patch versions are faulty/broken releases._
## 2.12.5
* **Internal**
* Fix incorrect `for...in` loop still causing `ember-script` issues.
## 2.12.4
* **Polish**
* Rest parameters now allocate the array before populating.
* **Internal**
* `for...in` loops have been changed to optimised `for` loops - better performance and no enumeration of protoype keys.
* Parts of the code generator have now been optimised thanks to [gaearon](https://github.com/gaearon).
## 2.12.3
* **Spec Compliancy**
* Optional `typeof` transformer checks for `undefined` before passing it to the helper.
* Class methods are now named.
## 2.12.2
* **Internal**
* Exclude nodes in function parameters and catch clauses from `isReferenced` check.
## 2.12.1
* **Internal**
* Add `.jsx` to list of allowed extensions.
## 2.12.0
* **Bug Fix**
* Support non-string JSX literals.
* **New Feature**
* Loose mode for some transformers that enables non-spec behaviour.
* **Internal**
* Uglify `--mangle sort` has been added to the build script, cutting minified scripts in half.
## 2.11.4
* **Internal**
* Make all dependency versions fixed.
## 2.11.3
* **Bug Fix**
* Allow a string to be passed as the `optional` option.
## 2.11.2
* **Bug Fix**
* Support esprima-style catch clause handlers.
* **Polish**
* Don't print a stacktrace for syntax errors in the CLI.
## 2.11.1
* **Bug Fix**
* Remove stray `console.log` outputting debug code.
* Remove `Dict` from `coreAliasing`.
## 2.11.0
* **Bug Fix**
* Fix unnecessary IIFE in default parameters on method calls.
* Add support for supers inside of closures.
* **New Feature**
* Add `--keep-module-id-extensions`/`keepModuleIdExtensions` option to keep extensions in module ids.
* **Polish**
* Special case single argument spread properties in `super` inside classes.
* Don't use a variable declaration for class declaration IFFE.
* Rename `inherits` helper parameters.
* `coreAliasing` transformer now aliases `Promise`, `Set`, `Map` and more. Thanks [@AluisioASG](https://github.com/AluisioASG).
## 2.10.1
* **Internal**
* Upgrade `core-js` to `0.4.4`.
* **New Feature**
* Added `--include-regenerator` option to CLI and `includeRegenerator` option to API that includes the regenerator runtime if necessary.
## 2.10.0
* **New Feature**
* Add `classesFastSuper` optional transformer that doesn't support parent getters and prototype changing.
* Add `forOfFast` transformer that speeds up `for...of` on arrays but produces more code.
* Add `--react-compat` to `bin/6to5`.
* **Spec Compliancy**
* Disallow setters without a single parameter.
* Add `configurable` and `writable` to defined properties.
* Use define instead of assignment for class methods.
* **Polish**
* Fix bin name in `6to5-node --help`.
* Fix shorthand `--whitelist` name in `bin/6to5`.
* **Internal**
* Hot code optimisation of traversal etc thanks to [gaearon](https://github.com/gaearon).
## 2.9.4
* **Bug Fix**
* Support `UpdateExpression`s as `MemberExpression` objects.
## 2.9.3
* **Bug Fix**
* Remove `exportsWildcard` helper in favor of `defaults`.
## 2.9.2
* **Bug Fix**
* Pass `exports` to `exportWildcard` helper to allow for use inside the optional runtime.
## 2.9.1
* **Bug Fix**
* Fix runtime generator breaking the helper inclusion loop.
## 2.9.0
* **Internal**
* Upgrade `acorn-6to5`.
* Now supports destructuring shorthand properties.
## 2.8.1
* **Bug Fix**
* Fix computed accessors on object literals.
## 2.8.0
* **New Feature**
* Add `commonStrict`, `amdStrict` and `umdStrict` module formatters that remove `module.exports` interop assignment.
* Add `--indent` option to the 6to5 CLI.
## 2.7.4
* **Polish**
* Inherit assignments from their declaration in destructuring.
* Properly align multi-declarator variable declarations.
## 2.7.3
* **Polish**

View File

@@ -1,6 +1,20 @@
# Contributing
Before contributing, please read the [code of conduct](https://github.com/6to5/6to5/blob/master/CODE_OF_CONDUCT.md).
Contributions are always welcome, no matter how large or small. Before contributing, please read the [code of conduct](https://github.com/6to5/6to5/blob/master/CODE_OF_CONDUCT.md).
## Developing
#### Workflow
* Fork the repository
* Clone your fork and change directory to it (`git clone git@github.com:yourUserName/6to5.git && cd 6to5`)
* Install the project dependencies (`make bootstrap`)
* Link your forked clone (`npm link`)
* Develop your changes ensuring you're fetching updates from upstream often
* Ensure the test are passing (`make test`)
* Create new pull request explaining your proposed change or reference an issue in your commit message
#### Code Standards
* **General**
* No ES6 syntax features or methods, exclusively ES5.

View File

@@ -1,12 +1,12 @@
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
export NODE_ENV = test
.PHONY: clean test test-cov test-clean lint test-travis test-simple test-all test-browser publish build bootstrap
.PHONY: clean test test-cov test-clean lint test-travis test-simple test-all test-browser publish build bootstrap publish-core
build:
mkdir -p dist
@@ -71,6 +71,9 @@ publish:
make test
read -p "Version: " version; \
npm version $$version --message "v%s"
make build
cp dist/6to5.min.js browser.js
cp dist/polyfill.min.js browser-polyfill.js
@@ -79,12 +82,21 @@ publish:
node bin/cache-templates
test -f templates.json
read -p "Version: " version; \
npm version $$version --message "v%s"
npm publish
git push --follow-tags
# generate
bin/generate-core-package-json >package2.json
mv package.json .package.json
mv package2.json package.json
npm publish
# restore
rm -rf package.json
mv .package.json package.json
rm -rf templates.json browser.js runtime.js browser-polyfill.js
bootstrap:

View File

@@ -1,8 +1,13 @@
# Notes
* Wildcard exports/imports wont normalise if `export default` is a non-object.
* Wildcard exports/imports wont normalise if `export default` is a non-object. See [#224](https://github.com/6to5/6to5/issues/224).
## 3.0.0 breaking changes
* Remove `allowImportExportEverywhere` option from acorn.
* Remove this shorthand from playground.
* Remove `super()` inside non-constructors - add descriptive error message.
* Split up ES5 getter/setter transforming and ES6 property methods into separate transformers.
* Add autoindentation.
* Move `super` transformation from classes into a separate transformer that also supports object expressions.
* Remove fast transformer backwards compatibility.

View File

@@ -1,9 +1,9 @@
var chokidar = require("chokidar");
var mkdirp = require("mkdirp");
var path = require("path");
var util = require("./util");
var fs = require("fs");
var _ = require("lodash");
var outputFileSync = require("output-file-sync");
var chokidar = require("chokidar");
var path = require("path");
var util = require("./util");
var fs = require("fs");
var _ = require("lodash");
module.exports = function (commander, filenames, opts) {
if (commander.sourceMapsInline) {
@@ -15,16 +15,13 @@ module.exports = function (commander, filenames, opts) {
var data = util.compile(src, { sourceMapName: dest });
var up = path.normalize(dest + "/..");
mkdirp.sync(up);
if (commander.sourceMaps) {
var mapLoc = dest + ".map";
data.code = util.addSourceMappingUrl(data.code, mapLoc);
fs.writeFileSync(mapLoc, JSON.stringify(data.map));
outputFileSync(mapLoc, JSON.stringify(data.map));
}
fs.writeFileSync(dest, data.code);
outputFileSync(dest, data.code);
console.log(src + " -> " + dest);
};

View File

@@ -15,14 +15,19 @@ commander.option("-e, --experimental", "Enable experimental support for proposed
commander.option("-p, --playground", "Enable playground support");
commander.option("-m, --modules [modules]", "Module formatter type to use [common]", "common");
commander.option("-w, --whitelist [whitelist]", "Whitelist of transformers to ONLY use", util.list);
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("--loose [list]", "List of transformers to enable their loose mode", 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("-I, --indent [width]", "Indent width [2]", 2);
commander.option("-a, --amd-module-ids", "Insert module id in AMD modules", false); // todo: remove in 3.0.0
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("-E, --include-regenerator", "Include the regenerator runtime if necessary", false);
commander.option("--keep-module-id-extensions", "Keep extensions when generating module ids", false);
commander.on("--help", function(){
var outKeys = function (title, obj) {
@@ -98,17 +103,26 @@ if (errors.length) {
//
exports.opts = {
sourceMapName: commander.outFile,
experimental: commander.experimental,
playground: commander.playground,
moduleIds: commander.amdModuleIds || commander.moduleIds,
blacklist: commander.blacklist,
whitelist: commander.whitelist,
sourceMap: commander.sourceMaps || commander.sourceMapsInline,
optional: commander.optional,
comments: !commander.removeComments,
runtime: commander.runtime,
modules: commander.modules
keepModuleIdExtensions: commander.keepModuleIdExtensions,
includeRegenerator: commander.includeRegenerator,
sourceMapName: commander.outFile,
experimental: commander.experimental,
reactCompat: commander.reactCompat,
playground: commander.playground,
moduleIds: commander.amdModuleIds || commander.moduleIds,
blacklist: commander.blacklist,
whitelist: commander.whitelist,
sourceMap: commander.sourceMaps || commander.sourceMapsInline,
optional: commander.optional,
comments: !commander.removeComments,
runtime: commander.runtime,
modules: commander.modules,
loose: commander.loose,
format: {
indent: {
style: util.repeat(parseInt(commander.indent))
}
}
};
var fn;

View File

@@ -20,7 +20,17 @@ exports.transform = function (filename, code, opts) {
opts = _.extend(opts || {}, index.opts);
opts.filename = filename;
var result = to5.transform(code, opts);
var result;
try {
result = to5.transform(code, opts);
} catch (e) {
if (e instanceof SyntaxError) {
console.error("SyntaxError:", e.message);
process.exit(1);
} else {
throw e;
}
}
result.filename = filename;
result.actual = code;
return result;

View File

@@ -10,29 +10,31 @@ var util = require("../lib/6to5/util");
var vm = require("vm");
var _ = require("lodash");
commander.option("-e, --eval [script]", "Evaluate script");
commander.option("-p, --print", "Evaluate script and print result");
commander.option("-i, --ignore [regex]", "Ignore all files that match this regex when using the require hook");
commander.option("-x, --extensions [extensions]", "List of extensions to hook into [.es6,.js]");
commander.option("-r, --experimental", "Enable experimental support for proposed ES7 features");
commander.option("-g, --playground", "Enable playground support");
commander.option("-c, --cache", "Cache compiled files and require paths");
var program = new commander.Command("6to5-node");
program.option("-e, --eval [script]", "Evaluate script");
program.option("-p, --print", "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]");
program.option("-r, --experimental", "Enable experimental support for proposed ES7 features");
program.option("-g, --playground", "Enable playground support");
program.option("-c, --cache", "Cache compiled files and require paths");
var pkg = require("../package.json");
commander.version(pkg.version);
commander.usage("[options] [ -e script | script.js ] [arguments]");
commander.parse(process.argv);
program.version(pkg.version);
program.usage("[options] [ -e script | script.js ] [arguments]");
program.parse(process.argv);
if (commander.cache) roadrunner.load();
if (program.cache) roadrunner.load();
//
to5.register({
experimental: commander.experimental,
extensions: commander.extensions,
playground: commander.playground,
ignore: commander.ignore,
cache: commander.cache && roadrunner.get("6to5")
experimental: program.experimental,
extensions: program.extensions,
playground: program.playground,
ignore: program.ignore,
cache: program.cache && roadrunner.get("6to5")
});
//
@@ -41,17 +43,17 @@ var _eval = function (code, filename) {
code = to5.transform(code, {
filename: filename,
blacklist: ["useStrict"],
experimental: commander.experimental,
playground: commander.playground
experimental: program.experimental,
playground: program.playground
}).code;
return vm.runInThisContext(code, filename);
};
if (commander.eval) {
var result = _eval(commander.eval, "eval");
if (commander.print) console.log(result);
if (program.eval) {
var result = _eval(program.eval, "eval");
if (program.print) console.log(result);
} else {
if (commander.args.length) {
if (program.args.length) {
// slice all arguments up to the first filename since they're 6to5 args that we handle
var args = process.argv.slice(2);
@@ -77,7 +79,7 @@ if (commander.eval) {
}
}
if (commander.cache) roadrunner.save();
if (program.cache) roadrunner.save();
function replStart() {
repl.start({
@@ -94,8 +96,8 @@ function replEval(code, context, filename, callback) {
var result;
try {
if (/^\((.*?)\n\)$/.test(code)) {
code = code.slice(1, -2); // remove "(" and "\n)"
if (code[0] === "(" && code[code.length - 1] === ")") {
code = code.slice(1, -1); // remove "(" and ")"
}
result = _eval(code, filename);

11
bin/generate-core-package-json Executable file
View File

@@ -0,0 +1,11 @@
#!/usr/bin/env node
var pkg = require("../package.json");
pkg.name += "-core";
delete pkg.dependencies.chokidar;
delete pkg.optionalDependencies;
delete pkg.devDependencies;
delete pkg.preferGlobal;
delete pkg.scripts;
delete pkg.bin;
console.log(JSON.stringify(pkg, null, " "));

View File

@@ -24,6 +24,7 @@ File.helpers = [
"prototype-properties",
"apply-constructor",
"tagged-template-literal",
"tagged-template-literal-loose",
"interop-require",
"to-array",
"sliced-to-array",
@@ -35,34 +36,38 @@ File.helpers = [
"async-to-generator",
"interop-require-wildcard",
"typeof",
"exports-wildcard",
"extends"
"extends",
"get"
];
File.excludeHelpersFromRuntime = [
"async-to-generator",
"typeof"
"typeof",
"tagged-template-literal-loose"
];
File.normaliseOptions = function (opts) {
opts = _.cloneDeep(opts || {});
_.defaults(opts, {
experimental: false,
reactCompat: false,
playground: false,
whitespace: true,
moduleIds: opts.amdModuleIds || false,
blacklist: [],
whitelist: [],
sourceMap: false,
optional: [],
comments: true,
filename: "unknown",
modules: "common",
runtime: false,
code: true,
ast: true
keepModuleIdExtensions: false,
includeRegenerator: false,
experimental: false,
reactCompat: false,
playground: false,
whitespace: true,
moduleIds: opts.amdModuleIds || false,
blacklist: [],
whitelist: [],
sourceMap: false,
optional: [],
comments: true,
filename: "unknown",
modules: "common",
runtime: false,
loose: [],
code: true,
ast: true
});
// normalise windows path separators to unix
@@ -70,6 +75,19 @@ File.normaliseOptions = function (opts) {
opts.blacklist = util.arrayify(opts.blacklist);
opts.whitelist = util.arrayify(opts.whitelist);
opts.optional = util.arrayify(opts.optional);
opts.loose = util.arrayify(opts.loose);
// todo: remove in 3.0.0
_.each({
fastForOf: "forOf",
classesFastSuper: "classes"
}, function (newTransformer, oldTransformer) {
if (_.contains(opts.optional, oldTransformer)) {
_.pull(opts.optional, oldTransformer);
opts.loose.push(newTransformer);
}
});
_.defaults(opts, {
moduleRoot: opts.sourceRoot
@@ -99,10 +117,15 @@ File.normaliseOptions = function (opts) {
transform._ensureTransformerNames("blacklist", opts.blacklist);
transform._ensureTransformerNames("whitelist", opts.whitelist);
transform._ensureTransformerNames("optional", opts.optional);
transform._ensureTransformerNames("loose", opts.loose);
return opts;
};
File.prototype.isLoose = function (key) {
return _.contains(this.opts.loose, key);
};
File.prototype.getTransformers = function () {
var file = this;
var transformers = [];

View File

@@ -61,39 +61,63 @@ Buffer.prototype.space = function () {
Buffer.prototype.removeLast = function (cha) {
if (!this.isLast(cha)) return;
this.buf = this.buf.slice(0, -1);
this.buf = this.buf.substr(0, this.buf.length - 1);
this.position.unshift(cha);
};
Buffer.prototype.newline = function (i, removeLast) {
if (this.format.compact) return;
if (_.isBoolean(i)) {
removeLast = i;
i = null;
}
removeLast = removeLast || false;
if (_.isNumber(i)) {
if (this.endsWith("{\n")) i--;
if (this.endsWith(util.repeat(i, "\n"))) return;
var self = this;
_.times(i, function () {
self.newline(null, removeLast);
});
while (i--) {
this._newline(removeLast);
}
return;
}
if (_.isBoolean(i)) {
removeLast = i;
}
this._newline(removeLast);
};
Buffer.prototype._newline = function (removeLast) {
if (removeLast && this.isLast("\n")) this.removeLast("\n");
this.removeLast(" ");
// remove whitespace if last character was a newline
this.buf = this.buf.replace(/\n +$/, "\n");
this._removeSpacesAfterLastNewline();
this._push("\n");
};
/**
* If buffer ends with a newline and some spaces after it, trim those spaces.
*/
Buffer.prototype._removeSpacesAfterLastNewline = function () {
var lastNewlineIndex = this.buf.lastIndexOf('\n');
if (lastNewlineIndex === -1)
return;
var index = this.buf.length - 1;
while (index > lastNewlineIndex) {
if (this.buf[index] !== ' ') {
break;
}
index--;
}
if (index === lastNewlineIndex) {
this.buf = this.buf.substring(0, index + 1);
}
};
Buffer.prototype.push = function (str, noIndent) {
if (this._indent && !noIndent && str !== "\n") {
// we have an indent level and we aren't pushing a newline
@@ -115,13 +139,18 @@ Buffer.prototype._push = function (str) {
};
Buffer.prototype.endsWith = function (str) {
return this.buf.slice(-str.length) === str;
var d = this.buf.length - str.length;
return d >= 0 && this.buf.lastIndexOf(str) === d;
};
Buffer.prototype.isLast = function (cha, trimRight) {
var buf = this.buf;
if (trimRight) buf = util.trimRight(buf);
var last = buf[buf.length - 1];
var chars = [].concat(cha);
return _.contains(chars, _.last(buf));
if (Array.isArray(cha)) {
return _.contains(cha, last);
} else {
return cha === last;
}
};

View File

@@ -125,7 +125,7 @@ CodeGenerator.prototype.print = function (node, parent, opts) {
var lines = 0;
if (node.start != null) {
if (node.start != null && !node._ignoreUserWhitespace) {
// user node
if (leading) {
lines = self.whitespace.getNewlinesBefore(node);

View File

@@ -62,7 +62,7 @@ exports.CallExpression = function (node, print) {
var separator = ",";
if (node._prettyPrint) {
if (node._prettyCall) {
separator += "\n";
this.newline();
this.indent();
@@ -74,7 +74,7 @@ exports.CallExpression = function (node, print) {
separator: separator
});
if (node._prettyPrint) {
if (node._prettyCall) {
this.newline();
this.dedent();
}

View File

@@ -1,4 +1,5 @@
var t = require("../../types");
var util = require("../../util");
var t = require("../../types");
exports.WithStatement = function (node, print) {
this.keyword("with");
@@ -106,7 +107,16 @@ exports.TryStatement = function (node, print) {
this.keyword("try");
print(node.block);
this.space();
print(node.handler);
// Esprima bug puts the catch clause in a `handlers` array.
// see https://code.google.com/p/esprima/issues/detail?id=433
// We run into this from regenerator generated ast.
if (node.handlers) {
print(node.handlers[0]);
} else {
print(node.handler);
}
if (node.finalizer) {
this.space();
this.push("finally ");
@@ -157,7 +167,24 @@ exports.DebuggerStatement = function () {
exports.VariableDeclaration = function (node, print, parent) {
this.push(node.kind + " ");
print.join(node.declarations, { separator: ", " });
var inits = 0;
var noInits = 0;
for (var i = 0; i < node.declarations.length; i++) {
if (node.declarations[i].init) {
inits++;
} else {
noInits++;
}
}
var sep = ",";
if (inits > noInits) { // more inits than noinits
sep += "\n" + util.repeat(node.kind.length + 1);
} else {
sep += " ";
}
print.join(node.declarations, { separator: sep });
if (!t.isFor(parent)) {
this.semicolon();

View File

@@ -6,14 +6,19 @@ var t = require("../../types");
var _ = require("lodash");
var find = function (obj, node, parent) {
if (!obj) return;
var result;
_.each(obj, function (fn, type) {
if (t["is" + type](node)) {
var types = Object.keys(obj);
for (var i = 0; i < types.length; i++) {
var type = types[i];
if (t.is(type, node)) {
var fn = obj[type];
result = fn(node, parent);
if (result != null) return false;
if (result != null) break;
}
});
}
return result;
};
@@ -23,13 +28,11 @@ function Node(node, parent) {
this.node = node;
}
Node.prototype.isUserWhitespacable = function () {
return t.isUserWhitespacable(this.node);
Node.isUserWhitespacable = function (node) {
return t.isUserWhitespacable(node);
};
Node.prototype.needsWhitespace = function (type) {
var parent = this.parent;
var node = this.node;
Node.needsWhitespace = function (node, parent, type) {
if (!node) return 0;
if (t.isExpressionStatement(node)) {
@@ -46,18 +49,15 @@ Node.prototype.needsWhitespace = function (type) {
return lines || 0;
};
Node.prototype.needsWhitespaceBefore = function () {
return this.needsWhitespace("before");
Node.needsWhitespaceBefore = function (node, parent) {
return Node.needsWhitespace(node, parent, "before");
};
Node.prototype.needsWhitespaceAfter = function () {
return this.needsWhitespace("after");
Node.needsWhitespaceAfter = function (node, parent) {
return Node.needsWhitespace(node, parent, "after");
};
Node.prototype.needsParens = function () {
var parent = this.parent;
var node = this.node;
Node.needsParens = function (node, parent) {
if (!parent) return false;
if (t.isNewExpression(parent) && parent.callee === node) {
@@ -72,10 +72,7 @@ Node.prototype.needsParens = function () {
return find(parens, node, parent);
};
Node.prototype.needsParensNoLineTerminator = function () {
var parent = this.parent;
var node = this.node;
Node.needsParensNoLineTerminator = function (node, parent) {
if (!parent) return false;
// no comments
@@ -95,11 +92,18 @@ Node.prototype.needsParensNoLineTerminator = function () {
return false;
};
_.each(Node.prototype, function (fn, key) {
Node[key] = function (node, parent) {
var n = new Node(node, parent);
_.each(Node, function (fn, key) {
Node.prototype[key] = function () {
// Avoid leaking arguments to prevent deoptimization
var args = new Array(arguments.length + 2);
var args = _.toArray(arguments).slice(2);
return n[key].apply(n, args);
args[0] = this.node;
args[1] = this.parent;
for (var i = 0; i < args.length; i++) {
args[i + 2] = arguments[i];
}
return Node[key].apply(null, args);
};
});

View File

@@ -21,6 +21,13 @@ _.each([
});
});
exports.UpdateExpression = function (node, parent) {
if (t.isMemberExpression(parent) && parent.object === node) {
// (foo++).test()
return true;
}
};
exports.ObjectExpression = function (node, parent) {
if (t.isExpressionStatement(parent)) {
// ({ foo: "bar" });

View File

@@ -62,11 +62,15 @@ _.each({
CallExpression: { after: 1 },
Literal: { after: 1 }
}, function (amounts, type) {
if (_.isNumber(amounts)) amounts = { after: amounts, before: amounts };
if (_.isNumber(amounts)) {
amounts = { after: amounts, before: amounts };
}
_.each(amounts, function (amount, key) {
exports[key].nodes[type] = function () {
return amount;
};
_.each([type].concat(t.FLIPPED_ALIAS_KEYS[type] || []), function (type) {
_.each(amounts, function (amount, key) {
exports[key].nodes[type] = function () {
return amount;
};
});
});
});

View File

@@ -1,33 +1,27 @@
module.exports = Position;
var _ = require("lodash");
function Position() {
this.line = 1;
this.column = 0;
}
Position.prototype.push = function (str) {
var self = this;
_.each(str, function (cha) {
if (cha === "\n") {
self.line++;
self.column = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] === "\n") {
this.line++;
this.column = 0;
} else {
self.column++;
this.column++;
}
});
}
};
Position.prototype.unshift = function (str) {
var self = this;
_.each(str, function (cha) {
if (cha === "\n") {
self.line--;
for (var i = 0; i < str.length; i++) {
if (str[i] === "\n") {
this.line--;
} else {
self.column--;
this.column--;
}
});
}
};

View File

@@ -1,25 +1,60 @@
module.exports = Whitespace;
var _ = require("lodash");
var _ = require("lodash");
/**
* Returns `i`th number from `base`, continuing from 0 when `max` is reached.
* Useful for shifting `for` loop by a fixed number but going over all items.
*
* @param {Number} i Current index in the loop
* @param {Number} base Start index for which to return 0
* @param {Number} max Array length
* @returns {Number} shiftedIndex
*/
function getLookupIndex(i, base, max) {
i += base;
if (i >= max)
i -= max;
return i;
}
function Whitespace(tokens, comments) {
this.tokens = _.sortBy(tokens.concat(comments), "start");
this.used = [];
this.used = {};
// Profiling this code shows that while generator passes over it, indexes
// returned by `getNewlinesBefore` and `getNewlinesAfter` are always increasing.
// We use this implementation detail for an optimization: instead of always
// starting to look from `this.tokens[0]`, we will start `for` loops from the
// previous successful match. We will enumerate all tokens—but the common
// case will be much faster.
this._lastFoundIndex = 0;
}
Whitespace.prototype.getNewlinesBefore = function (node) {
var startToken;
var endToken;
var tokens = this.tokens;
var token;
for (var j = 0; j < tokens.length; j++) {
// optimize for forward traversal by shifting for loop index
var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length);
token = tokens[i];
_.each(tokens, function (token, i) {
// this is the token this node starts with
if (node.start === token.start) {
startToken = tokens[i - 1];
endToken = token;
return false;
this._lastFoundIndex = i;
break;
}
});
}
return this.getNewlinesBetween(startToken, endToken);
};
@@ -28,35 +63,47 @@ 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];
_.each(tokens, function (token, i) {
// this is the token this node ends with
if (node.end === token.end) {
startToken = token;
endToken = tokens[i + 1];
return false;
this._lastFoundIndex = i;
break;
}
});
}
if (endToken.type.type === "eof") {
return 1;
} else {
return this.getNewlinesBetween(startToken, endToken);
var lines = this.getNewlinesBetween(startToken, endToken);
if (node.type === "Line" && !lines) {
// line comment
return 1;
} else {
return lines;
}
}
};
Whitespace.prototype.getNewlinesBetween = function (startToken, endToken) {
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 (!_.contains(this.used, line)) {
this.used.push(line);
if (typeof this.used[line] === 'undefined') {
this.used[line] = true;
lines++;
}
}
return lines;
};
};

View File

@@ -1,4 +1,5 @@
// Required to safely use 6to5/register within a browserify codebase.
// required to safely use 6to5/register within a browserify codebase
module.exports = function () {};
require("./polyfill");

View File

@@ -21,51 +21,6 @@ sourceMapSupport.install({
}
});
//
var blacklist = [];
var blacklistTest = function (transformer, code) {
try {
if (_.isFunction(code)) {
code();
} else {
new Function(code);
}
blacklist.push(transformer);
} catch (err) {
if (err.name !== "SyntaxError") throw err;
}
};
blacklistTest("arrayComprehension", "var foo = [for (foo of bar) foo * foo];");
blacklistTest("generatorComprehension", "var foo = (for (foo of bar) foo * foo)");
blacklistTest("arrowFunctions", "var foo = x => x * x;");
blacklistTest("classes", "class Foo {}");
blacklistTest("computedPropertyNames", "var foo = { [foo]: bar };");
blacklistTest("constants", function () {
try {
new Function("const foo = 'foo';\nfoo = 'wow';");
} catch (err) {
return; // constants are supported
}
throw new SyntaxError;
});
blacklistTest("defaultParamaters", "var foo = function (bar = 0) {};");
blacklistTest("destructuring", "var { x, y } = { x: 0, y: 0 };");
blacklistTest("forOf", "for (var foo of bar) {}");
blacklistTest("generators", "function* foo() {}\nasync function bar() {}"); // generators/async functions delegated to same transformer
blacklistTest("letScoping", "let foo = 0;");
blacklistTest("modules", 'import foo from "from";');
blacklistTest("propertyMethodAssignment", "{ get foo() {} }");
blacklistTest("propertyNameShorthand", "var foo = { x, y };");
blacklistTest("restParameters", "function foo(...bar) {}");
blacklistTest("spread", "foo(...bar);");
blacklistTest("templateLiterals", "var foo = `foo`;");
blacklistTest("unicodeRegex", function () { new RegExp("foo", "u"); });
//
var transformOpts = {};
var ignoreRegex = /node_modules/;
var onlyRegex;
@@ -95,7 +50,6 @@ var loader = function (m, filename) {
result = result || to5.transformFileSync(filename, _.extend({
whitelist: whitelist,
blacklist: blacklist,
sourceMap: true,
ast: false
}, transformOpts));
@@ -123,7 +77,7 @@ var hookExtensions = function (_exts) {
});
};
hookExtensions([".es6", ".es", ".js"]);
hookExtensions(util.canCompile.EXTENSIONS);
module.exports = function (opts) {
// normalise options

View File

@@ -20,7 +20,7 @@ module.exports = function (namespace) {
_.each(File.helpers, function (name) {
if (_.contains(File.excludeHelpersFromRuntime, name)) {
return false;
return;
}
var key = t.identifier(t.toIdentifier(name));

View File

@@ -0,0 +1,23 @@
var t = require("../../types");
module.exports = function build(node, buildBody) {
var self = node.blocks.shift();
if (!self) return;
var child = build(node, buildBody);
if (!child) {
// last item
child = buildBody();
// add a filter as this is our final stop
if (node.filter) {
child = t.ifStatement(node.filter, t.blockStatement([child]));
}
}
return t.forOfStatement(
t.variableDeclaration("let", [t.variableDeclarator(self.left)]),
self.right,
t.blockStatement([child])
);
};

View File

@@ -0,0 +1,43 @@
var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
module.exports = function (node, file, scope) {
var key = t.toComputedKey(node, node.key);
if (!t.isLiteral(key)) return node; // we can't set a function id with this
var id = t.toIdentifier(key.value);
key = t.identifier(id);
var selfReference = false;
var outerDeclar = scope.get(id, true);
traverse(node, {
enter: function (node, parent, scope) {
// check if this node is an identifier that matches the same as our function id
if (!t.isIdentifier(node, { name: id })) return;
// check if this node is the one referenced
if (!t.isReferenced(node, parent)) return;
// check that we don't have a local variable declared as that removes the need
// for the wrapper
var localDeclar = scope.get(id, true);
if (localDeclar !== outerDeclar) return;
selfReference = true;
this.stop();
}
}, scope);
if (selfReference) {
node.value = util.template("property-method-assignment-wrapper", {
FUNCTION: node.value,
FUNCTION_ID: key,
FUNCTION_KEY: file.generateUidIdentifier(id, scope),
WRAPPER_KEY: file.generateUidIdentifier(id + "Wrapper", scope)
});
} else {
node.value.id = key;
}
};

View File

@@ -0,0 +1,29 @@
var traverse = require("../../traverse");
var t = require("../../types");
module.exports = function (node, callId) {
node.async = false;
node.generator = true;
traverse(node, {
enter: function (node) {
if (t.isFunction(node)) this.skip();
if (t.isAwaitExpression(node)) {
node.type = "YieldExpression";
}
}
});
var call = t.callExpression(callId, [node]);
if (t.isFunctionDeclaration(node)) {
var declar = t.variableDeclaration("var", [
t.variableDeclarator(node.id, call)
]);
declar._blockHoist = true;
return declar;
} else {
return call;
}
};

View File

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

View File

@@ -156,8 +156,10 @@ DefaultFormatter.prototype.getModuleName = function () {
filenameRelative = filenameRelative.replace(sourceRootRegEx, "");
}
// remove extension
filenameRelative = filenameRelative.replace(/\.(.*?)$/, "");
if (!opts.keepModuleIdExtensions) {
// remove extension
filenameRelative = filenameRelative.replace(/\.(.*?)$/, "");
}
moduleName += filenameRelative;
@@ -217,7 +219,8 @@ DefaultFormatter.prototype._exportSpecifier = function (getRef, specifier, node,
};
DefaultFormatter.prototype._exportsWildcard = function (objectIdentifier) {
return t.expressionStatement(t.callExpression(this.file.addHelper("exports-wildcard"), [
return t.expressionStatement(t.callExpression(this.file.addHelper("defaults"), [
t.identifier("exports"),
t.callExpression(this.file.addHelper("interop-require-wildcard"), [objectIdentifier])
]));
};
@@ -241,13 +244,13 @@ DefaultFormatter.prototype.exportDeclaration = function (node, nodes) {
var assign;
if (t.isVariableDeclaration(declar)) {
for (var i in declar.declarations) {
for (var i = 0; i < declar.declarations.length; i++) {
var decl = declar.declarations[i];
decl.init = this._exportsAssign(decl.id, decl.init, node).expression;
var newDeclar = t.variableDeclaration(declar.kind, [decl]);
if (i === "0") t.inherits(newDeclar, declar);
if (i === 0) t.inherits(newDeclar, declar);
nodes.push(newDeclar);
}
} else {

View File

@@ -0,0 +1,12 @@
var util = require("../../util");
module.exports = function (Parent) {
var Constructor = function () {
this.noInteropExport = true;
Parent.apply(this, arguments);
};
util.inherits(Constructor, Parent);
return Constructor;
};

View File

@@ -0,0 +1 @@
module.exports = require("./_strict")(require("./amd"));

View File

@@ -7,8 +7,8 @@ var t = require("../../types");
var _ = require("lodash");
function AMDFormatter() {
DefaultFormatter.apply(this, arguments);
this.ids = {};
CommonFormatter.apply(this, arguments);
this.ids = {};
}
util.inherits(AMDFormatter, DefaultFormatter);
@@ -101,7 +101,7 @@ AMDFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
};
AMDFormatter.prototype.exportDeclaration = function (node) {
if (node.default) {
if (node.default && !this.noInteropExport) {
this.passModuleArg = true;
}

View File

@@ -0,0 +1 @@
module.exports = require("./_strict")(require("./common"));

View File

@@ -61,7 +61,7 @@ CommonJSFormatter.prototype.importDeclaration = function (node, nodes) {
};
CommonJSFormatter.prototype.exportDeclaration = function (node, nodes) {
if (node.default && !this.exportIdentifier) {
if (node.default && !this.noInteropRequire && !this.noInteropExport) {
var declar = node.declaration;
var assign;

View File

@@ -1,7 +1,7 @@
module.exports = SystemFormatter;
var AMDFormatter = require("./amd");
var useStrict = require("../transformers/use-strict");
var useStrict = require("../helpers/use-strict");
var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
@@ -171,7 +171,7 @@ SystemFormatter.prototype.transform = function (ast) {
handlerBody.push(returnStatement);
if (useStrict._has(block)) {
if (useStrict.has(block)) {
handlerBody.unshift(block.body.shift());
}

View File

@@ -0,0 +1 @@
module.exports = require("./_strict")(require("./umd"));

View File

@@ -31,17 +31,18 @@ UMDFormatter.prototype.transform = function (ast) {
var factory = t.functionExpression(null, args, t.blockStatement(body));
// runner
// amd
var defineArgs = [t.literal("exports")];
if (this.passModuleArg) defineArgs.push(t.literal("module"));
defineArgs = defineArgs.concat(names);
defineArgs = [t.arrayExpression(defineArgs)];
// typeof exports !== "undefined" && typeof module !== "undefined"
var testExports = t.binaryExpression("!==", t.unaryExpression("typeof", t.identifier("exports"), true), t.literal("undefined")),
testModule = t.binaryExpression("!==", t.unaryExpression("typeof", t.identifier("module"), true), t.literal("undefined")),
commonTests = this.passModuleArg ? t.logicalExpression("&&", testExports, testModule) : testExports;
// common
var testExports = util.template("test-exports");
var testModule = util.template("test-module");
var commonTests = this.passModuleArg ? t.logicalExpression("&&", testExports, testModule) : testExports;
var commonArgs = [t.identifier("exports")];
if (this.passModuleArg) commonArgs.push(t.identifier("module"));
@@ -49,6 +50,12 @@ UMDFormatter.prototype.transform = function (ast) {
return t.callExpression(t.identifier("require"), [name]);
}));
// globals
//var umdArgs = [];
//
var moduleName = this.getModuleName();
if (moduleName) defineArgs.unshift(t.literal(moduleName));

View File

@@ -0,0 +1,3 @@
if (SUPER_NAME != null) {
SUPER_NAME.apply(this, arguments);
}

View File

@@ -1,3 +1,3 @@
if (SUPER_NAME !== null) {
SUPER_NAME.apply(this, arguments);
if (Object.getPrototypeOf(CLASS_NAME) !== null) {
Object.getPrototypeOf(CLASS_NAME).apply(this, arguments);
}

View File

@@ -1,7 +0,0 @@
(function (obj) {
for (var i in obj) {
if (exports[i] !== undefined) {
exports[i] = obj[i];
}
}
})

View File

@@ -0,0 +1,13 @@
for (var LOOP_OBJECT = OBJECT,
IS_ARRAY = Array.isArray(LOOP_OBJECT),
INDEX = 0,
LOOP_OBJECT = IS_ARRAY ? LOOP_OBJECT : LOOP_OBJECT[Symbol.iterator]();;) {
if (IS_ARRAY) {
if (INDEX >= LOOP_OBJECT.length) break;
ID = LOOP_OBJECT[INDEX++];
} else {
INDEX = LOOP_OBJECT.next();
if (INDEX.done) break;
ID = INDEX.value;
}
}

View File

@@ -0,0 +1,23 @@
(function get(object, property, receiver) {
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc && desc.writable) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
});

View File

@@ -1,14 +1,14 @@
(function (child, parent) {
if (typeof parent !== "function" && parent !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof parent);
(function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
child.prototype = Object.create(parent && parent.prototype, {
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: child,
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (parent) child.__proto__ = parent;
if (superClass) subClass.__proto__ = superClass;
})

View File

@@ -1,5 +0,0 @@
(function (KEY) {
CONTENT;
return KEY;
})(OBJECT);

View File

@@ -1 +0,0 @@
Object.defineProperties(OBJECT, PROPS);

View File

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

View File

@@ -0,0 +1,4 @@
(function (strings, raw) {
strings.raw = raw;
return strings;
});

View File

@@ -0,0 +1 @@
typeof exports !== "undefined"

View File

@@ -0,0 +1 @@
typeof module !== "undefined"

View File

@@ -20,7 +20,7 @@ transform.fromAst = function (ast, code, opts) {
};
transform._ensureTransformerNames = function (type, keys) {
for (var i in keys) {
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!_.has(transform.transformers, key)) {
throw new ReferenceError("unknown transformer " + key + " specified in " + type);
@@ -31,15 +31,19 @@ transform._ensureTransformerNames = function (type, keys) {
transform.transformers = {};
transform.moduleFormatters = {
common: require("./modules/common"),
system: require("./modules/system"),
ignore: require("./modules/ignore"),
amd: require("./modules/amd"),
umd: require("./modules/umd")
commonStrict: require("./modules/common-strict"),
umdStrict: require("./modules/umd-strict"),
amdStrict: require("./modules/amd-strict"),
common: require("./modules/common"),
system: require("./modules/system"),
ignore: require("./modules/ignore"),
amd: require("./modules/amd"),
umd: require("./modules/umd")
};
_.each({
specNoForInOfAssignment: require("./transformers/spec-no-for-in-of-assignment"),
specSetters: require("./transformers/spec-setters"),
// playground
methodBinding: require("./transformers/playground-method-binding"),
@@ -57,13 +61,12 @@ _.each({
arrowFunctions: require("./transformers/es6-arrow-functions"),
classes: require("./transformers/es6-classes"),
computedPropertyNames: require("./transformers/es6-computed-property-names"),
objectSpread: require("./transformers/es7-object-spread"),
exponentiationOperator: require("./transformers/es7-exponentiation-operator"),
spread: require("./transformers/es6-spread"),
templateLiterals: require("./transformers/es6-template-literals"),
propertyMethodAssignment: require("./transformers/es6-property-method-assignment"),
computedPropertyNames: require("./transformers/es6-computed-property-names"),
destructuring: require("./transformers/es6-destructuring"),
defaultParameters: require("./transformers/es6-default-parameters"),
forOf: require("./transformers/es6-for-of"),

View File

@@ -65,7 +65,7 @@ Transformer.prototype.transform = function (file) {
if (exit) fn = fns.exit;
if (!fn) return;
return fn(node, parent, file, scope);
return fn.call(this, node, parent, file, scope);
};
};

View File

@@ -1,4 +1,4 @@
var useStrict = require("./use-strict");
var useStrict = require("../helpers/use-strict");
var _ = require("lodash");
// Priority:
@@ -12,13 +12,13 @@ exports.BlockStatement =
exports.Program = {
exit: function (node) {
var hasChange = false;
for (var i in node.body) {
for (var i = 0; i < node.body.length; i++) {
var bodyNode = node.body[i];
if (bodyNode && bodyNode._blockHoist != null) hasChange = true;
}
if (!hasChange) return;
useStrict._wrap(node, function () {
useStrict.wrap(node, function () {
var nodePriorities = _.groupBy(node.body, function (bodyNode) {
var priority = bodyNode._blockHoist;
if (priority == null) priority = 1;

View File

@@ -1,14 +1,16 @@
var useStrict = require("./use-strict");
var useStrict = require("../helpers/use-strict");
var t = require("../../types");
exports.secondPass = true;
exports.BlockStatement =
exports.Program = function (node) {
if (!node._declarations) return;
var kinds = {};
var kind;
useStrict._wrap(node, function () {
useStrict.wrap(node, function () {
for (var i in node._declarations) {
var declar = node._declarations[i];

View File

@@ -1,38 +1,26 @@
var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
var nameMethod = require("../helpers/name-method");
var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
exports.ClassDeclaration = function (node, parent, file, scope) {
var closure = true;
if (t.isProgram(parent) || t.isBlockStatement(parent)) {
closure = false;
}
var factory = new Class(node, file, scope, closure);
var newNode = factory.run();
if (factory.closure) {
if (closure) {
// declaration in an expression context...
// export default class Foo {}
scope.push({
kind: "var",
key: node.id.key,
id: node.id
});
return t.assignmentExpression("=", node.id, newNode);
} else {
// has a super class or PrivateDeclaration etc
return t.variableDeclaration("let", [
t.variableDeclarator(node.id, newNode)
]);
}
} else {
return newNode;
}
return new Class(node, file, scope, true).run();
};
exports.ClassExpression = function (node, parent, file, scope) {
return new Class(node, file, scope, true).run();
if (!node.id) {
if (t.isProperty(parent) && parent.value === node && !parent.computed && t.isIdentifier(parent.key)) {
// var o = { foo: class {} };
node.id = parent.key;
}
if (t.isVariableDeclarator(parent) && t.isIdentifier(parent.id)) {
// var foo = class {};
node.id = parent.id;
}
}
return new Class(node, file, scope, false).run();
};
/**
@@ -44,11 +32,11 @@ exports.ClassExpression = function (node, parent, file, scope) {
* @param {Boolean} closure
*/
function Class(node, file, scope, closure) {
this.closure = closure;
this.scope = scope;
this.node = node;
this.file = file;
function Class(node, file, scope, isStatement) {
this.isStatement = isStatement;
this.scope = scope;
this.node = node;
this.file = file;
this.hasInstanceMutators = false;
this.hasStaticMutators = false;
@@ -58,6 +46,7 @@ function Class(node, file, scope, closure) {
this.hasConstructor = false;
this.className = node.id || file.generateUidIdentifier("class", scope);
this.superName = node.superClass;
this.isLoose = file.isLoose("classes");
}
/**
@@ -75,25 +64,32 @@ Class.prototype.run = function () {
var body = this.body = [];
var constructor = t.functionExpression(null, [], t.blockStatement([]));
if (this.node.id) constructor.id = className;
var constructor;
if (this.node.id) {
constructor = t.functionDeclaration(className, [], t.blockStatement([]));
body.push(constructor);
} else {
constructor = t.functionExpression(null, [], t.blockStatement([]));
body.push(t.variableDeclaration("var", [
t.variableDeclarator(className, constructor)
]));
}
this.constructor = constructor;
body.push(t.variableDeclaration("let", [
t.variableDeclarator(className, constructor)
]));
var closureParams = [];
var closureArgs = [];
//
if (superName) {
this.closure = true;
closureArgs.push(superName);
// so we're only evaluating it once
var superRef = this.scope.generateUidBasedOnNode(superName, this.file);
body.unshift(t.variableDeclaration("var", [
t.variableDeclarator(superRef, superName)
]));
superName = superRef;
if (!t.isIdentifier(superName)) {
var superRef = this.scope.generateUidBasedOnNode(superName, this.file);
superName = superRef;
}
closureParams.push(superName);
this.superName = superName;
body.push(t.expressionStatement(t.callExpression(file.addHelper("inherits"), [className, superName])));
@@ -103,19 +99,25 @@ Class.prototype.run = function () {
t.inheritsComments(body[0], this.node);
if (this.closure) {
if (body.length === 1) {
// only a constructor so no need for a closure container
return constructor;
} else {
body.push(t.returnStatement(className));
return t.callExpression(
t.functionExpression(null, [], t.blockStatement(body)),
[]
);
}
var init;
if (body.length === 1) {
// only a constructor so no need for a closure container
init = t.toExpression(constructor);
} else {
return body;
body.push(t.returnStatement(className));
init = t.callExpression(
t.functionExpression(null, closureParams, t.blockStatement(body)),
closureArgs
);
}
if (this.isStatement) {
return t.variableDeclaration("let", [
t.variableDeclarator(className, init)
]);
} else {
return init;
}
};
@@ -129,27 +131,31 @@ Class.prototype.buildBody = function () {
var superName = this.superName;
var classBody = this.node.body.body;
var body = this.body;
var self = this;
for (var i in classBody) {
for (var i = 0; i < classBody.length; i++) {
var node = classBody[i];
if (t.isMethodDefinition(node)) {
self.replaceInstanceSuperReferences(node);
this.replaceSuperReferences(node);
if (node.key.name === "constructor") {
self.pushConstructor(node);
this.pushConstructor(node);
} else {
self.pushMethod(node);
this.pushMethod(node);
}
} else if (t.isPrivateDeclaration(node)) {
self.closure = true;
this.closure = true;
body.unshift(node);
}
}
// we have no constructor, we have a super, and the super doesn't appear to be falsy
if (!this.hasConstructor && superName && !t.isFalsyExpression(superName)) {
constructor.body.body.push(util.template("class-super-constructor-call", {
SUPER_NAME: superName
var defaultConstructorTemplate = "class-super-constructor-call";
if (this.isLoose) defaultConstructorTemplate += "-loose";
constructor.body.body.push(util.template(defaultConstructorTemplate, {
CLASS_NAME: className,
SUPER_NAME: this.superName
}, true));
}
@@ -157,15 +163,11 @@ Class.prototype.buildBody = function () {
var staticProps;
if (this.hasInstanceMutators) {
var protoId = util.template("prototype-identifier", {
CLASS_NAME: className
});
instanceProps = util.buildDefineProperties(this.instanceMutatorMap, protoId);
instanceProps = util.buildDefineProperties(this.instanceMutatorMap);
}
if (this.hasStaticMutators) {
staticProps = util.buildDefineProperties(this.staticMutatorMap, className);
staticProps = util.buildDefineProperties(this.staticMutatorMap);
}
if (instanceProps || staticProps) {
@@ -192,39 +194,75 @@ Class.prototype.pushMethod = function (node) {
var kind = node.kind;
if (kind === "") {
// method
nameMethod(node, this.file, this.scope);
var className = this.className;
if (!node.static) className = t.memberExpression(className, t.identifier("prototype"));
methodName = t.memberExpression(className, methodName, node.computed);
if (this.isLoose) {
// use assignments instead of define properties for loose classes
var expr = t.expressionStatement(t.assignmentExpression("=", methodName, node.value));
t.inheritsComments(expr, node);
this.body.push(expr);
} else {
// mutator
var mutatorMap = this.instanceMutatorMap;
if (node.static) {
this.hasStaticMutators = true;
mutatorMap = this.staticMutatorMap;
} else {
this.hasInstanceMutators = true;
var className = this.className;
if (!node.static) className = t.memberExpression(className, t.identifier("prototype"));
methodName = t.memberExpression(className, methodName, node.computed);
var expr = t.expressionStatement(t.assignmentExpression("=", methodName, node.value));
t.inheritsComments(expr, node);
this.body.push(expr);
return;
}
util.pushMutatorMap(mutatorMap, methodName, kind, node);
kind = "value";
}
var mutatorMap = this.instanceMutatorMap;
if (node.static) {
this.hasStaticMutators = true;
mutatorMap = this.staticMutatorMap;
} else {
this.hasInstanceMutators = true;
}
util.pushMutatorMap(mutatorMap, methodName, kind, node.computed, node);
};
/**
* Given a `methodNode`, produce a `MemberExpression` super class reference.
* Gets a node representing the super class value of the named property.
*
* @param {Node} methodNode MethodDefinition
* @param {Node} node Identifier
* @param {Node} parent
* @example
*
* _get(Object.getPrototypeOf(CLASS.prototype), "METHOD", this)
*
* @param {Node} property
* @param {boolean} isStatic
* @param {boolean} isComputed
*
* @returns {Node}
*/
Class.prototype.superIdentifier = function (methodNode, id, parent) {
Class.prototype.superProperty = function (property, isStatic, isComputed, thisExpression) {
return t.callExpression(
this.file.addHelper("get"),
[
t.callExpression(
t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")),
[
isStatic ? this.className : t.memberExpression(this.className, t.identifier("prototype"))
]
),
isComputed ? property : t.literal(property.name),
thisExpression
]
);
};
/**
* Description
*
* @param {Object} node
* @param {Object} id
* @param {Object} parent
* @returns {Object}
*/
Class.prototype.looseSuperProperty = function (methodNode, id, parent) {
var methodName = methodNode.key;
var superName = this.superName || t.identifier("Function");
@@ -262,25 +300,119 @@ Class.prototype.superIdentifier = function (methodNode, id, parent) {
* @param {Node} methodNode MethodDefinition
*/
Class.prototype.replaceInstanceSuperReferences = function (methodNode) {
Class.prototype.replaceSuperReferences = function (methodNode) {
var method = methodNode.value;
var self = this;
var self = this;
traverse(method, {
enter: function (node, parent) {
if (t.isIdentifier(node, { name: "super" })) {
return self.superIdentifier(methodNode, node, parent);
} else if (t.isCallExpression(node)) {
var callee = node.callee;
var topLevelThisReference;
traverseLevel(method, true);
if (topLevelThisReference) {
method.body.body.unshift(t.variableDeclaration("var", [
t.variableDeclarator(topLevelThisReference, t.thisExpression())
]));
}
function traverseLevel(node, topLevel) {
traverse(node, {
enter: function (node, parent) {
if (t.isFunction(node) && !t.isArrowFunctionExpression(node)) {
// we need to call traverseLevel again so we're context aware
traverseLevel(node, false);
return this.skip();
}
if (t.isProperty(node, { method: true }) || t.isMethodDefinition(node)) {
// break on object methods
return this.skip();
}
var getThisReference = function () {
if (topLevel) {
// top level so `this` is the instance
return t.thisExpression();
} else {
// not in the top level so we need to create a reference
return topLevelThisReference = topLevelThisReference || self.file.generateUidIdentifier("this");
}
};
var callback = specHandle;
if (self.isLoose) callback = looseHandle;
return callback(getThisReference, node, parent);
}
});
}
function looseHandle(getThisReference, node, parent) {
if (t.isIdentifier(node, { name: "super" })) {
return self.looseSuperProperty(methodNode, node, parent);
} else if (t.isCallExpression(node)) {
var callee = node.callee;
if (!t.isMemberExpression(callee)) return;
if (callee.object.name !== "super") return;
// super.test(); -> ClassName.prototype.MethodName.call(this);
t.appendToMemberExpression(callee, t.identifier("call"));
node.arguments.unshift(getThisReference());
}
}
function specHandle(getThisReference, node, parent) {
var property;
var computed;
var args;
if (t.isIdentifier(node, { name: "super" })) {
if (!(t.isMemberExpression(parent) && !parent.computed && parent.property === node)) {
throw self.file.errorWithNode(node, "illegal use of bare super");
}
} else if (t.isCallExpression(node)) {
var callee = node.callee;
if (t.isIdentifier(callee, { name: "super" })) {
// super(); -> _get(Object.getPrototypeOf(ClassName), "MethodName", this).call(this);
property = methodNode.key;
computed = methodNode.computed;
args = node.arguments;
} else {
if (!t.isMemberExpression(callee)) return;
if (callee.object.name !== "super") return;
// super.test(); -> ClassName.prototype.MethodName.call(this);
t.appendToMemberExpression(callee, t.identifier("call"));
node.arguments.unshift(t.thisExpression());
// super.test(); -> _get(Object.getPrototypeOf(ClassName.prototype), "test", this).call(this);
property = callee.property;
computed = callee.computed;
args = node.arguments;
}
} else if (t.isMemberExpression(node)) {
if (!t.isIdentifier(node.object, { name: "super" })) return;
// super.name; -> _get(Object.getPrototypeOf(ClassName.prototype), "name", this);
property = node.property;
computed = node.computed;
}
});
if (!property) return;
var thisReference = getThisReference();
var superProperty = self.superProperty(property, methodNode.static, computed, thisReference);
if (args) {
if (args.length === 1 && t.isSpreadElement(args[0])) {
// super(...arguments);
return t.callExpression(
t.memberExpression(superProperty, t.identifier("apply")),
[thisReference, args[0].argument]
);
} else {
return t.callExpression(
t.memberExpression(superProperty, t.identifier("call")),
[thisReference].concat(args)
);
}
} else {
return superProperty;
}
}
};
/**
@@ -290,7 +422,7 @@ Class.prototype.replaceInstanceSuperReferences = function (methodNode) {
*/
Class.prototype.pushConstructor = function (method) {
if (method.kind !== "") {
if (method.kind) {
throw this.file.errorWithNode(method, "illegal kind for constructor method");
}
@@ -302,8 +434,9 @@ Class.prototype.pushConstructor = function (method) {
t.inherits(construct, fn);
t.inheritsComments(construct, method);
construct.defaults = fn.defaults;
construct.params = fn.params;
construct.body = fn.body;
construct.rest = fn.rest;
construct._ignoreUserWhitespace = true;
construct.defaults = fn.defaults;
construct.params = fn.params;
construct.body = fn.body;
construct.rest = fn.rest;
};

View File

@@ -2,29 +2,66 @@ var t = require("../../types");
exports.ObjectExpression = function (node, parent, file, scope) {
var hasComputed = false;
var prop;
var key;
var i;
for (i in node.properties) {
hasComputed = t.isProperty(node.properties[i], { computed: true });
for (var i = 0; i < node.properties.length; i++) {
hasComputed = t.isProperty(node.properties[i], { computed: true, kind: "init" });
if (hasComputed) break;
}
if (!hasComputed) return;
var initProps = [];
var objId = scope.generateUidBasedOnNode(parent, file);
//
var body = [];
var container = t.functionExpression(null, [], t.blockStatement(body));
container._aliasFunction = true;
//
var callback = spec;
if (file.isLoose("computedPropertyNames")) callback = loose;
var result = callback(node, body, objId, initProps, file);
if (result) return result;
//
body.unshift(t.variableDeclaration("var", [
t.variableDeclarator(objId, t.objectExpression(initProps))
]));
body.push(t.returnStatement(objId));
return t.callExpression(container, []);
};
var loose = function (node, body, objId) {
for (var i = 0; i < node.properties.length; i++) {
var prop = node.properties[i];
body.push(t.expressionStatement(
t.assignmentExpression(
"=",
t.memberExpression(objId, prop.key, prop.computed),
prop.value
)
));
}
};
var spec = function (node, body, objId, initProps, file) {
var props = node.properties;
var prop, key;
// normalise key
for (i in props) {
for (var i = 0; i < props.length; i++) {
prop = props[i];
if (prop.kind !== "init") continue;
key = prop.key;
if (!prop.computed && t.isIdentifier(key)) {
@@ -34,17 +71,16 @@ exports.ObjectExpression = function (node, parent, file, scope) {
// add all non-computed properties and `__proto__` properties to the initializer
var initProps = [];
var broken = false;
for (i in props) {
for (i = 0; i < props.length; i++) {
prop = props[i];
if (prop.computed) {
broken = true;
}
if (!broken || t.isLiteral(t.toComputedKey(prop, prop.key), { value: "__proto__" })) {
if (prop.kind !== "init" || !broken || t.isLiteral(t.toComputedKey(prop, prop.key), { value: "__proto__" })) {
initProps.push(prop);
props[i] = null;
}
@@ -53,7 +89,7 @@ exports.ObjectExpression = function (node, parent, file, scope) {
// add a simple assignment for all Symbol member expressions due to symbol polyfill limitations
// otherwise use Object.defineProperty
for (i in props) {
for (i = 0; i < props.length; i++) {
prop = props[i];
if (!prop) continue;
@@ -84,14 +120,4 @@ exports.ObjectExpression = function (node, parent, file, scope) {
return first;
}
}
//
body.unshift(t.variableDeclaration("var", [
t.variableDeclarator(objId, t.objectExpression(initProps))
]));
body.push(t.returnStatement(objId));
return t.callExpression(container, []);
};

View File

@@ -44,7 +44,7 @@ exports.ForStatement = function (node, parent, file) {
}
if (t.isVariableDeclaration(child, { kind: "const" })) {
for (var i in child.declarations) {
for (var i = 0; i < child.declarations.length; i++) {
var declar = child.declarations[i];
var ids = getIds(declar);

View File

@@ -1,7 +1,6 @@
var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
var _ = require("lodash");
exports.Function = function (node, parent, file, scope) {
if (!node.defaults || !node.defaults.length) return;
@@ -12,10 +11,26 @@ exports.Function = function (node, parent, file, scope) {
});
var iife = false;
var i;
var def;
for (i in node.defaults) {
var checkTDZ = function (ids) {
var check = function (node, parent) {
if (!t.isIdentifier(node) || !t.isReferenced(node, parent)) return;
if (ids.indexOf(node.name) >= 0) {
throw file.errorWithNode(node, "Temporal dead zone - accessing a variable before it's initialized");
}
if (scope.has(node.name, true)) {
iife = true;
}
};
check(def, node);
traverse(def, { enter: check });
};
for (var i = 0; i < node.defaults.length; i++) {
def = node.defaults[i];
if (!def) continue;
@@ -23,25 +38,13 @@ exports.Function = function (node, parent, file, scope) {
// temporal dead zone check - here we prevent accessing of params that
// are to the right - ie. uninitialized parameters
_.each(ids.slice(i), function (ids) {
var check = function (node, parent) {
if (!t.isIdentifier(node) || !t.isReferenced(node, parent)) return;
if (ids.indexOf(node.name) >= 0) {
throw file.errorWithNode(node, "Temporal dead zone - accessing a variable before it's initialized");
}
if (scope.has(node.name)) {
iife = true;
}
};
check(def, node);
traverse(def, { enter: check });
});
var rightIds = ids.slice(i);
for (var i2 = 0; i2 < rightIds.length; i2++) {
checkTDZ(rightIds[i2]);
}
// we're accessing a variable that's already defined within this function
var has = scope.get(param.name);
var has = scope.get(param.name, true);
if (has && node.params.indexOf(has) < 0) {
iife = true;
}
@@ -54,7 +57,7 @@ exports.Function = function (node, parent, file, scope) {
var lastNonDefaultParam = 0;
for (i in node.defaults) {
for (i = 0; i < node.defaults.length; i++) {
def = node.defaults[i];
if (!def) {
lastNonDefaultParam = +i + 1;

View File

@@ -46,12 +46,12 @@ var pushAssignmentPattern = function (opts, nodes, pattern, parentId) {
};
var pushObjectPattern = function (opts, nodes, pattern, parentId) {
for (var i in pattern.properties) {
for (var i = 0; i < pattern.properties.length; i++) {
var prop = pattern.properties[i];
if (t.isSpreadProperty(prop)) {
// get all the keys that appear in this object before the current spread
var keys = [];
for (var i2 in pattern.properties) {
for (var i2 = 0; i2 < pattern.properties.length; i2++) {
var prop2 = pattern.properties[i2];
if (i2 >= i) break;
@@ -88,7 +88,7 @@ var pushArrayPattern = function (opts, nodes, pattern, parentId) {
var i;
var hasSpreadElement = false;
for (i in pattern.elements) {
for (i = 0; i < pattern.elements.length; i++) {
if (t.isSpreadElement(pattern.elements[i])) {
hasSpreadElement = true;
break;
@@ -103,7 +103,7 @@ var pushArrayPattern = function (opts, nodes, pattern, parentId) {
]));
parentId = _parentId;
for (i in pattern.elements) {
for (i = 0; i < pattern.elements.length; i++) {
var elem = pattern.elements[i];
if (!elem) continue;
@@ -134,7 +134,7 @@ var pushPattern = function (opts) {
var file = opts.file;
var scope = opts.scope;
if (!t.isMemberExpression(parentId) && !t.isIdentifier(parentId)) {
if (!t.isArrayExpression(parentId) && !t.isMemberExpression(parentId) && !t.isIdentifier(parentId)) {
var key = scope.generateUidBasedOnNode(parentId, file);
nodes.push(t.variableDeclaration("var", [
@@ -278,7 +278,7 @@ exports.VariableDeclaration = function (node, parent, file, scope) {
var declar;
var hasPattern = false;
for (i in node.declarations) {
for (i = 0; i < node.declarations.length; i++) {
declar = node.declarations[i];
if (t.isPattern(declar.id)) {
hasPattern = true;
@@ -287,7 +287,7 @@ exports.VariableDeclaration = function (node, parent, file, scope) {
}
if (!hasPattern) return;
for (i in node.declarations) {
for (i = 0; i < node.declarations.length; i++) {
declar = node.declarations[i];
var patternId = declar.init;
@@ -300,17 +300,24 @@ exports.VariableDeclaration = function (node, parent, file, scope) {
file: file,
scope: scope
};
if (t.isPattern(pattern) && patternId) {
pushPattern(opts);
if (+i !== node.declarations.length - 1) {
// we aren't the last declarator so let's just make the
// last transformed node inherit from us
t.inherits(nodes[nodes.length - 1], declar);
}
} else {
nodes.push(buildVariableAssign(opts, declar.id, declar.init));
nodes.push(t.inherits(buildVariableAssign(opts, declar.id, declar.init), declar));
}
}
if (!t.isProgram(parent) && !t.isBlockStatement(parent)) {
declar = null;
for (i in nodes) {
for (i = 0; i < nodes.length; i++) {
node = nodes[i];
declar = declar || t.variableDeclaration(node.kind, []);

View File

@@ -2,15 +2,79 @@ var util = require("../../util");
var t = require("../../types");
exports.ForOfStatement = function (node, parent, file, scope) {
var callback = spec;
if (file.isLoose("forOf")) callback = loose;
var build = callback(node, parent, file, scope);
var declar = build.declar;
var loop = build.loop;
var block = loop.body;
// inherit comments from the original loop
t.inheritsComments(loop, node);
// ensure that it's a block so we can take all it's statemetns
t.ensureBlock(node);
// add the value declaration to the new loop body
if (declar){
if (build.shouldUnshift) {
block.body.unshift(declar);
} else {
block.body.push(declar);
}
}
// push the rest of the original loop body onto our new body
block.body = block.body.concat(node.body.body);
return loop;
};
var loose = function (node, parent, file, scope) {
var left = node.left;
var declar, id;
if (t.isIdentifier(left) || t.isPattern(left)) {
// for (i of test), for ({ i } of test)
id = left;
} else if (t.isVariableDeclaration(left)) {
// for (var i of test)
id = left.declarations[0].id;
declar = t.variableDeclaration(left.kind, [
t.variableDeclarator(id)
]);
} else {
throw file.errorWithNode(left, "Unknown node type " + left.type + " in ForOfStatement");
}
var loop = util.template("for-of-loose", {
LOOP_OBJECT: file.generateUidIdentifier("iterator", scope),
IS_ARRAY: file.generateUidIdentifier("isArray", scope),
OBJECT: node.right,
INDEX: file.generateUidIdentifier("i", scope),
ID: id
});
return {
shouldUnshift: true,
declar: declar,
loop: loop
};
};
var spec = function (node, parent, file, scope) {
var left = node.left;
var declar;
var stepKey = file.generateUidIdentifier("step", scope);
var stepValue = t.memberExpression(stepKey, t.identifier("value"));
if (t.isIdentifier(left)) {
if (t.isIdentifier(left) || t.isPattern(left)) {
// for (i of test), for ({ i } of test)
declar = t.expressionStatement(t.assignmentExpression("=", left, stepValue));
} else if (t.isVariableDeclaration(left)) {
// for (var i of test)
declar = t.variableDeclaration(left.kind, [
t.variableDeclarator(left.declarations[0].id, stepValue)
]);
@@ -18,18 +82,14 @@ exports.ForOfStatement = function (node, parent, file, scope) {
throw file.errorWithNode(left, "Unknown node type " + left.type + " in ForOfStatement");
}
var node2 = util.template("for-of", {
var loop = util.template("for-of", {
ITERATOR_KEY: file.generateUidIdentifier("iterator", scope),
STEP_KEY: stepKey,
OBJECT: node.right
});
t.inheritsComments(node2, node);
t.ensureBlock(node);
var block = node2.body;
block.body.push(declar);
block.body = block.body.concat(node.body.body);
return node2;
return {
declar: declar,
loop: loop
};
};

View File

@@ -1,3 +1,9 @@
var regenerator = require("regenerator");
exports.ast = {
before: require("regenerator").transform
before: function (ast, file) {
regenerator.transform(ast, {
includeRuntime: file.opts.includeRegenerator && "if used"
});
}
};

View File

@@ -25,7 +25,7 @@ var isVar = function (node, parent) {
};
var standardiseLets = function (declars) {
for (var i in declars) {
for (var i = 0; i < declars.length; i++) {
delete declars[i]._let;
}
};
@@ -231,12 +231,10 @@ LetScoping.prototype.getInfo = function () {
}
};
var i;
var declar;
for (i in opts.declarators) {
for (var i = 0; i < opts.declarators.length; i++) {
declar = opts.declarators[i];
opts.declarators.push(declar);
var keys = t.getIds(declar, true);
_.each(keys, duplicates);
@@ -246,14 +244,17 @@ LetScoping.prototype.getInfo = function () {
opts.keys = opts.keys.concat(keys);
}
for (i in block.body) {
declar = block.body[i];
if (!isLet(declar, block)) continue;
if (block.body) {
for (i = 0; i < block.body.length; i++) {
declar = block.body[i];
if (!isLet(declar, block)) continue;
_.each(t.getIds(declar, true), function (id, key) {
duplicates(id, key);
opts.keys.push(key);
});
var declars = t.getIds(declar, true);
for (var key in declars) {
duplicates(declars[key], key);
opts.keys.push(key);
}
}
}
return opts;
@@ -411,7 +412,7 @@ LetScoping.prototype.pushDeclar = function (node) {
var replace = [];
for (var i in node.declarations) {
for (var i = 0; i < node.declarations.length; i++) {
var declar = node.declarations[i];
if (!declar.init) continue;

View File

@@ -10,7 +10,7 @@ exports.ImportDeclaration = function (node, parent, file) {
var nodes = [];
if (node.specifiers.length) {
for (var i in node.specifiers) {
for (var i = 0; i < node.specifiers.length; i++) {
file.moduleFormatter.importSpecifier(node.specifiers[i], node, nodes, parent);
}
} else {
@@ -39,7 +39,7 @@ exports.ExportDeclaration = function (node, parent, file) {
file.moduleFormatter.exportDeclaration(node, nodes, parent);
} else {
for (var i in node.specifiers) {
for (var i = 0; i < node.specifiers.length; i++) {
file.moduleFormatter.exportSpecifier(node.specifiers[i], node, nodes, parent);
}
}

View File

@@ -1,59 +1,23 @@
var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
var nameMethod = require("../helpers/name-method");
var util = require("../../util");
var t = require("../../types");
exports.Property = function (node, parent, file, scope) {
if (!node.method) return;
node.method = false;
var key = t.toComputedKey(node, node.key);
if (!t.isLiteral(key)) return; // we can't set a function id with this
var id = t.toIdentifier(key.value);
key = t.identifier(id);
var selfReference = false;
var outerDeclar = scope.get(id, true);
traverse(node, {
enter: function (node, parent, scope) {
// check if this node is an identifier that matches the same as our function id
if (!t.isIdentifier(node, { name: id })) return;
// check if this node is the one referenced
if (!t.isReferenced(node, parent)) return;
// check that we don't have a local variable declared as that removes the need
// for the wrapper
var localDeclar = scope.get(id, true);
if (localDeclar !== outerDeclar) return;
selfReference = true;
this.stop();
}
}, scope);
if (selfReference) {
node.value = util.template("property-method-assignment-wrapper", {
FUNCTION: node.value,
FUNCTION_ID: key,
FUNCTION_KEY: file.generateUidIdentifier(id, scope),
WRAPPER_KEY: file.generateUidIdentifier(id + "Wrapper", scope)
});
} else {
node.value.id = key;
}
nameMethod(node, file, scope);
};
exports.ObjectExpression = function (node, parent, file, scope) {
exports.ObjectExpression = function (node) {
var mutatorMap = {};
var hasAny = false;
node.properties = node.properties.filter(function (prop) {
if (prop.kind === "get" || prop.kind === "set") {
hasAny = true;
util.pushMutatorMap(mutatorMap, prop.key, prop.kind, prop.value);
util.pushMutatorMap(mutatorMap, prop.key, prop.kind, prop.computed, prop.value);
return false;
} else {
return true;
@@ -62,21 +26,8 @@ exports.ObjectExpression = function (node, parent, file, scope) {
if (!hasAny) return;
if (node.properties.length) {
var objId = scope.generateUidBasedOnNode(parent, file);
return util.template("object-define-properties-closure", {
KEY: objId,
OBJECT: node,
CONTENT: util.template("object-define-properties", {
OBJECT: objId,
PROPS: util.buildDefineProperties(mutatorMap)
})
});
} else {
return util.template("object-define-properties", {
OBJECT: node,
PROPS: util.buildDefineProperties(mutatorMap)
});
}
return t.callExpression(
t.memberExpression(t.identifier("Object"), t.identifier("defineProperties")),
[node, util.buildDefineProperties(mutatorMap)]
);
};

View File

@@ -10,27 +10,42 @@ exports.Function = function (node, parent, file) {
t.ensureBlock(node);
var argsId = t.identifier("arguments");
// otherwise `arguments` will be remapped in arrow functions
argsId._ignoreAliasFunctions = true;
var start = t.literal(node.params.length);
var key = file.generateUidIdentifier("key");
var len = file.generateUidIdentifier("len");
var arrKey = key;
var arrLen = len;
if (node.params.length) {
arrKey = t.binaryExpression("-", arrKey, start);
// this method has additional params, so we need to subtract
// the index of the current argument position from the
// position in the array that we want to populate
arrKey = t.binaryExpression("-", key, start);
// we need to work out the size of the array that we're
// going to store all the rest parameters in, if there
// are less arguments than params then the array can be
// constructed with <1 which will cause an error
arrLen = t.conditionalExpression(
t.binaryExpression(">", len, start),
t.binaryExpression("-", len, start),
t.literal(0)
);
}
node.body.body.unshift(
t.variableDeclaration("var", [
t.variableDeclarator(rest, t.arrayExpression([]))
]),
util.template("rest", {
ARGUMENTS: argsId,
ARRAY_KEY: arrKey,
ARRAY_LEN: arrLen,
START: start,
ARRAY: rest,
KEY: key
KEY: key,
LEN: len,
})
);
};

View File

@@ -6,7 +6,7 @@ var getSpreadLiteral = function (spread, file) {
};
var hasSpread = function (nodes) {
for (var i in nodes) {
for (var i = 0; i < nodes.length; i++) {
if (t.isSpreadElement(nodes[i])) {
return true;
}
@@ -25,7 +25,7 @@ var build = function (props, file) {
_props = [];
};
for (var i in props) {
for (var i = 0; i < props.length; i++) {
var prop = props[i];
if (t.isSpreadElement(prop)) {
push();

View File

@@ -11,16 +11,18 @@ exports.TaggedTemplateExpression = function (node, parent, file) {
var strings = [];
var raw = [];
for (var i in quasi.quasis) {
for (var i = 0; i < quasi.quasis.length; i++) {
var elem = quasi.quasis[i];
strings.push(t.literal(elem.value.cooked));
raw.push(t.literal(elem.value.raw));
}
args.push(t.callExpression(file.addHelper("tagged-template-literal"), [
t.arrayExpression(strings),
t.arrayExpression(raw)
]));
strings = t.arrayExpression(strings);
raw = t.arrayExpression(raw);
var templateName = "tagged-template-literal";
if (file.isLoose("templateLiterals")) templateName += "-loose";
args.push(t.callExpression(file.addHelper(templateName), [strings, raw]));
args = args.concat(quasi.expressions);
@@ -31,7 +33,7 @@ exports.TemplateLiteral = function (node) {
var nodes = [];
var i;
for (i in node.quasis) {
for (i = 0; i < node.quasis.length; i++) {
var elem = node.quasis[i];
nodes.push(t.literal(elem.value.cooked));
@@ -47,7 +49,7 @@ exports.TemplateLiteral = function (node) {
var root = buildBinaryExpression(nodes.shift(), nodes.shift());
for (i in nodes) {
for (i = 0; i < nodes.length; i++) {
root = buildBinaryExpression(root, nodes[i]);
}

View File

@@ -1,6 +1,7 @@
var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
var buildComprehension = require("../helpers/build-comprehension");
var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
exports.experimental = true;
@@ -22,7 +23,7 @@ var build = function (node, parent, file, scope) {
var returnStatement = body.pop();
body.push(exports._build(node, function () {
body.push(buildComprehension(node, function () {
return util.template("array-push", {
STATEMENT: node.body,
KEY: uid
@@ -33,28 +34,6 @@ var build = function (node, parent, file, scope) {
return container;
};
exports._build = function (node, buildBody) {
var self = node.blocks.shift();
if (!self) return;
var child = exports._build(node, buildBody);
if (!child) {
// last item
child = buildBody();
// add a filter as this is our final stop
if (node.filter) {
child = t.ifStatement(node.filter, t.blockStatement([child]));
}
}
return t.forOfStatement(
t.variableDeclaration("let", [t.variableDeclarator(self.left)]),
self.right,
t.blockStatement([child])
);
};
exports.ComprehensionExpression = function (node, parent, file, scope) {
if (node.generator) return;

View File

@@ -1,4 +1,4 @@
var arrayComprehension = require("./es7-array-comprehension");
var buildComprehension = require("../helpers/build-comprehension");
var t = require("../../types");
exports.experimental = true;
@@ -10,7 +10,7 @@ exports.ComprehensionExpression = function (node) {
var container = t.functionExpression(null, [], t.blockStatement(body), true);
container._aliasFunction = true;
body.push(arrayComprehension._build(node, function () {
body.push(buildComprehension(node, function () {
return t.expressionStatement(t.yieldExpression(node.body));
}));

View File

@@ -8,7 +8,7 @@ exports.ObjectExpression = function (node, parent, file) {
var hasSpread = false;
var i;
var prop;
for (i in node.properties) {
for (i = 0; i < node.properties.length; i++) {
prop = node.properties[i];
if (t.isSpreadProperty(prop)) {
hasSpread = true;
@@ -26,7 +26,7 @@ exports.ObjectExpression = function (node, parent, file) {
props = [];
};
for (i in node.properties) {
for (i = 0; i < node.properties.length; i++) {
prop = node.properties[i];
if (t.isSpreadProperty(prop)) {
push();

View File

@@ -1,4 +1,5 @@
var bluebirdCoroutines = require("./optional-bluebird-coroutines");
var remapAsyncToGenerator = require("../helpers/remap-async-to-generator");
var bluebirdCoroutines = require("./optional-bluebird-coroutines");
exports.optional = true;
@@ -7,5 +8,5 @@ exports.manipulateOptions = bluebirdCoroutines.manipulateOptions;
exports.Function = function (node, parent, file) {
if (!node.async || node.generator) return;
return bluebirdCoroutines._Function(node, file.addHelper("async-to-generator"));
return remapAsyncToGenerator(node, file.addHelper("async-to-generator"));
};

View File

@@ -1,5 +1,5 @@
var traverse = require("../../traverse");
var t = require("../../types");
var remapAsyncToGenerator = require("../helpers/remap-async-to-generator");
var t = require("../../types");
exports.manipulateOptions = function (opts) {
opts.experimental = true;
@@ -8,36 +8,12 @@ exports.manipulateOptions = function (opts) {
exports.optional = true;
exports._Function = function (node, callId) {
node.async = false;
node.generator = true;
traverse(node, {
enter: function (node) {
if (t.isFunction(node)) this.skip();
if (t.isAwaitExpression(node)) {
node.type = "YieldExpression";
}
}
});
var call = t.callExpression(callId, [node]);
if (t.isFunctionDeclaration(node)) {
var declar = t.variableDeclaration("var", [
t.variableDeclarator(node.id, call)
]);
declar._blockHoist = true;
return declar;
} else {
return call;
}
};
exports.Function = function (node, parent, file) {
if (!node.async || node.generator) return;
var id = file.addImport("bluebird");
return exports._Function(node, t.memberExpression(id, t.identifier("coroutine")));
return remapAsyncToGenerator(
node,
t.memberExpression(file.addImport("bluebird"), t.identifier("coroutine"))
);
};

View File

@@ -8,6 +8,15 @@ var coreHas = function (node) {
return node.name !== "_" && _.has(core, node.name);
};
var ALIASABLE_CONSTRUCTORS = [
"Symbol",
"Promise",
"Map",
"WeakMap",
"Set",
"WeakSet"
];
exports.optional = true;
exports.ast = {
@@ -31,8 +40,8 @@ exports.ast = {
this.skip();
return t.prependToMemberExpression(node, file._coreId);
}
} else if (t.isIdentifier(node) && !t.isMemberExpression(parent) && t.isReferenced(node, parent) && coreHas(node)) {
// new Promise -> new _core.Promise
} else if (t.isIdentifier(node) && !t.isMemberExpression(parent) && t.isReferenced(node, parent) && _.contains(ALIASABLE_CONSTRUCTORS, node.name)) {
// Symbol() -> _core.Symbol(); new Promise -> new _core.Promise
return t.memberExpression(file._coreId, node);
} else if (t.isCallExpression(node)) {
// arr[Symbol.iterator]() -> _core.$for.getIterator(arr)

View File

@@ -44,7 +44,7 @@ exports.ExpressionStatement = function (node, parent, file) {
exports.ObjectExpression = function (node, parent, file) {
var proto;
for (var i in node.properties) {
for (var i = 0; i < node.properties.length; i++) {
var prop = node.properties[i];
if (isProtoKey(prop)) {

View File

@@ -3,7 +3,19 @@ var t = require("../../types");
exports.optional = true;
exports.UnaryExpression = function (node, parent, file) {
this.skip();
if (node.operator === "typeof") {
return t.callExpression(file.addHelper("typeof"), [node.argument]);
var call = t.callExpression(file.addHelper("typeof"), [node.argument]);
if (t.isIdentifier(node.argument)) {
var undefLiteral = t.literal("undefined");
return t.conditionalExpression(
t.binaryExpression("===", t.unaryExpression("typeof", node.argument), undefLiteral),
undefLiteral,
call
);
} else {
return call;
}
}
};

View File

@@ -6,9 +6,11 @@ var isMemo = function (node) {
return is;
};
var getPropRef = function (nodes, prop, file, scope) {
if (t.isIdentifier(prop)) {
return t.literal(prop.name);
var getPropRef = function (nodes, member, file, scope) {
var prop = member.property;
var key = t.toComputedKey(member, member.property);
if (t.isLiteral(key)) {
return key;
} else {
var temp = scope.generateUidBasedOnNode(prop, file);
nodes.push(t.variableDeclaration("var", [
@@ -54,7 +56,7 @@ exports.ExpressionStatement = function (node, parent, file, scope) {
var left = expr.left;
var obj = getObjRef(nodes, left.object, file, scope);
var prop = getPropRef(nodes, left.property, file, scope);
var prop = getPropRef(nodes, left, file, scope);
nodes.push(t.ifStatement(
buildHasOwn(obj, prop, file),
@@ -72,7 +74,7 @@ exports.AssignmentExpression = function (node, parent, file, scope) {
var left = node.left;
var obj = getObjRef(nodes, left.object, file, scope);
var prop = getPropRef(nodes, left.property, file, scope);
var prop = getPropRef(nodes, left, file, scope);
nodes.push(t.logicalExpression(
"&&",

View File

@@ -5,6 +5,7 @@
var esutils = require("esutils");
var t = require("../../types");
var _ = require("lodash");
exports.XJSIdentifier = function (node) {
if (esutils.keyword.isIdentifierName(node.name)) {
@@ -61,11 +62,16 @@ exports.XJSOpeningElement = {
}
}
var props = node.attributes;
if (props.length) {
var attribs = node.attributes;
if (attribs.length) {
var _props = [];
var objs = [];
// so basically in order to support spread elements we
// loop over all the attributes, breaking on spreads
// we then push a new object containing all prior attributes
// to an array for later processing
var pushProps = function () {
if (!_props.length) return;
@@ -73,8 +79,8 @@ exports.XJSOpeningElement = {
_props = [];
};
while (props.length) {
var prop = props.shift();
while (attribs.length) {
var prop = attribs.shift();
if (t.isXJSSpreadAttribute(prop)) {
pushProps();
objs.push(prop.argument);
@@ -86,22 +92,25 @@ exports.XJSOpeningElement = {
pushProps();
if (objs.length === 1) {
props = objs[0];
// only one object
attribs = objs[0];
} else {
// looks like we have multiple objects
if (!t.isObjectExpression(objs[0])) {
objs.unshift(t.objectExpression([]));
}
props = t.callExpression(
// spread it
attribs = t.callExpression(
t.memberExpression(t.identifier("React"), t.identifier("__spread")),
objs
);
}
} else {
props = t.literal(null);
attribs = t.literal(null);
}
args.push(props);
args.push(attribs);
if (reactCompat) {
if (tagName && isTag(tagName)) {
@@ -125,19 +134,18 @@ exports.XJSOpeningElement = {
exports.XJSElement = {
exit: function (node) {
var callExpr = node.openingElement;
var i;
for (i in node.children) {
for (var i = 0; i < node.children.length; i++) {
var child = node.children[i];
if (t.isLiteral(child)) {
if (t.isLiteral(child) && _.isString(child.value)) {
var lines = child.value.split(/\r\n|\n|\r/);
for (i in lines) {
var line = lines[i];
for (var i2 = 0; i2 < lines.length; i2++) {
var line = lines[i2];
var isFirstLine = i === "0";
var isLastLine = +i === lines.length - 1;
var isFirstLine = i2 === 0;
var isLastLine = i2 === lines.length - 1;
// replace rendered whitespace tabs with spaces
var trimmedLine = line.replace(/\t/g, " ");
@@ -166,7 +174,7 @@ exports.XJSElement = {
}
if (callExpr.arguments.length >= 3) {
callExpr._prettyPrint = true;
callExpr._prettyCall = true;
}
return t.inherits(callExpr, node);
@@ -200,7 +208,7 @@ var addDisplayName = function (id, call) {
var props = first.properties;
var safe = true;
for (var i in props) {
for (var i = 0; i < props.length; i++) {
prop = props[i];
if (t.isIdentifier(prop.key, { name: "displayName" })) {
safe = false;

View File

@@ -0,0 +1,6 @@
exports.MethodDefinition =
exports.Property = function (node, parent, file) {
if (node.kind === "set" && node.value.params.length !== 1) {
throw file.errorWithNode(node.value, "Setters must have only one parameter");
}
};

View File

@@ -1,26 +1,9 @@
var t = require("../../types");
exports._has = function (node) {
var first = node.body[0];
return t.isExpressionStatement(first) && t.isLiteral(first.expression, { value: "use strict" });
};
exports._wrap = function (node, callback) {
var useStrictNode;
if (exports._has(node)) {
useStrictNode = node.body.shift();
}
callback();
if (useStrictNode) {
node.body.unshift(useStrictNode);
}
};
var useStrict = require("../helpers/use-strict");
var t = require("../../types");
exports.ast = {
exit: function (ast) {
if (!exports._has(ast.program)) {
if (!useStrict.has(ast.program)) {
ast.program.body.unshift(t.expressionStatement(t.literal("use strict")));
}
}

View File

@@ -4,15 +4,101 @@ var Scope = require("./scope");
var t = require("../types");
var _ = require("lodash");
function TraversalContext(previousContext) {
this.didSkip = false;
this.didRemove = false;
this.didStop = false;
this.didFlatten = previousContext ? previousContext.didFlatten : false;
}
TraversalContext.prototype.flatten = function () {
this.didFlatten = true;
};
TraversalContext.prototype.remove = function () {
this.didRemove = true;
this.skip();
};
TraversalContext.prototype.skip = function () {
this.didSkip = true;
};
TraversalContext.prototype.stop = function () {
this.didStop = true;
this.skip();
};
TraversalContext.prototype.maybeReplace = function (result, obj, key, node) {
if (result === false) return node;
if (result == null) return node;
var isArray = Array.isArray(result);
// inherit comments from original node to the first replacement node
var inheritTo = result;
if (isArray) inheritTo = result[0];
if (inheritTo) t.inheritsComments(inheritTo, node);
// replace the node
node = obj[key] = result;
// we're replacing a statement or block node with an array of statements so we better
// ensure that it's a block
if (isArray && _.contains(t.STATEMENT_OR_BLOCK_KEYS, key) && !t.isBlockStatement(obj)) {
t.ensureBlock(obj, key);
}
if (isArray) {
this.flatten();
}
return node;
};
TraversalContext.prototype.visit = function (obj, key, opts, scope, parent) {
var node = obj[key];
if (!node) return;
// type is blacklisted
if (opts.blacklist && opts.blacklist.indexOf(node.type) > -1) return;
var result;
var ourScope = scope;
if (t.isScope(node)) ourScope = new Scope(node, scope);
// enter
if (opts.enter) {
result = opts.enter.call(this, node, parent, ourScope);
node = this.maybeReplace(result, obj, key, node);
if (this.didRemove) {
obj[key] = null;
this.flatten();
}
// stop traversal
if (this.didSkip) return;
}
// traverse node
traverse(node, opts, ourScope);
// exit
if (opts.exit) {
result = opts.exit.call(this, node, parent, ourScope);
node = this.maybeReplace(result, obj, key, node);
}
};
function traverse(parent, opts, scope) {
// falsy node
if (!parent) return;
// array of nodes
if (_.isArray(parent)) {
_.each(parent, function (node) {
traverse(node, opts, scope);
});
if (Array.isArray(parent)) {
for (var i = 0; i < parent.length; i++)
traverse(parent[i], opts, scope);
return;
}
@@ -21,99 +107,21 @@ function traverse(parent, opts, scope) {
if (!keys) return;
opts = opts || {};
var context = null;
var stopped = false;
for (var i in keys) {
var key = keys[i];
for (var j = 0; j < keys.length; j++) {
var key = keys[j];
var nodes = parent[key];
if (!nodes) continue;
var flatten = false;
var handle = function (obj, key) {
var node = obj[key];
if (!node) return;
// type is blacklisted
if (opts.blacklist && opts.blacklist.indexOf(node.type) > -1) return;
// replace node
var maybeReplace = function (result) {
if (result === false) return;
if (result == null) return;
var isArray = _.isArray(result);
// inherit comments from original node to the first replacement node
var inheritTo = result;
if (isArray) inheritTo = result[0];
if (inheritTo) t.inheritsComments(inheritTo, node);
// replace the node
node = obj[key] = result;
if (isArray) flatten = true;
// we're replacing a statement or block node with an array of statements so we better
// ensure that it's a block
if (isArray && _.contains(t.STATEMENT_OR_BLOCK_KEYS, key) && !t.isBlockStatement(obj)) {
t.ensureBlock(obj, key);
}
};
var skipped = false;
var removed = false;
var context = {
stop: function () {
skipped = stopped = true;
},
skip: function () {
skipped = true;
},
remove: function () {
this.skip();
removed = true;
}
};
//
var ourScope = scope;
if (t.isScope(node)) ourScope = new Scope(node, scope);
// enter
if (opts.enter) {
var result = opts.enter.call(context, node, parent, ourScope);
maybeReplace(result);
if (removed) {
obj[key] = null;
flatten = true;
}
// stop iteration
if (skipped) return;
if (Array.isArray(nodes)) {
for (var k = 0; k < nodes.length; k++) {
context = new TraversalContext(context);
context.visit(nodes, k, opts, scope, parent);
if (context.didStop) return;
}
// traverse node
traverse(node, opts, ourScope);
// exit
if (opts.exit) {
maybeReplace(opts.exit.call(context, node, parent, ourScope));
}
};
if (_.isArray(nodes)) {
for (i in nodes) {
handle(nodes, i);
if (stopped) return;
}
if (flatten) {
if (context && context.didFlatten) {
parent[key] = _.flatten(parent[key]);
if (key === "body") {
@@ -122,8 +130,9 @@ function traverse(parent, opts, scope) {
}
}
} else {
handle(parent, key);
if (stopped) return;
context = new TraversalContext(context);
context.visit(parent, key, opts, scope, parent);
if (context.didStop) return;
}
}
}

View File

@@ -24,7 +24,13 @@ function Scope(block, parent) {
}
var vars = require("jshint/src/vars");
Scope.defaultDeclarations = _.flatten([vars.newEcmaIdentifiers, vars.node, vars.ecmaIdentifiers, vars.reservedVars].map(_.keys));
Scope.defaultDeclarations = _.flatten([
vars.newEcmaIdentifiers,
vars.node,
vars.ecmaIdentifiers,
vars.reservedVars
].map(_.keys));
Scope.add = function (node, references) {
if (!node) return;

View File

@@ -9,6 +9,7 @@
"ExpressionStatement": ["expression"],
"File": ["program", "comments", "tokens"],
"FunctionExpression": ["id", "params", "body", "generator"],
"FunctionDeclaration": ["id", "params", "body", "generator"],
"Identifier": ["name"],
"IfStatement": ["test", "consequent", "alternate"],
"ImportDeclaration": ["specifiers", "source"],
@@ -16,6 +17,7 @@
"Literal": ["value"],
"LogicalExpression": ["operator", "left", "right"],
"MemberExpression": ["object", "property", "computed"],
"MethodDefinition": ["key", "value", "computed", "kind"],
"NewExpression": ["callee", "arguments"],
"ObjectExpression": ["properties"],
"Program": ["body"],

View File

@@ -7,14 +7,25 @@ t.NATIVE_TYPE_NAMES = ["Array", "Object", "Number", "Boolean", "Date", "Array",
//
var addAssert = function (type, is) {
/**
* Registers `is[Type]` and `assert[Type]` generated functions for a given `type`.
* Pass `skipAliasCheck` to force it to directly compare `node.type` with `type`.
*
* @param {String} type
* @param {Boolean?} skipAliasCheck
*/
function registerType(type, skipAliasCheck) {
var is = t["is" + type] = function (node, opts) {
return t.is(type, node, opts, skipAliasCheck);
};
t["assert" + type] = function (node, opts) {
opts = opts || {};
if (!is(node, opts)) {
throw new Error("Expected type " + JSON.stringify(type) + " with option " + JSON.stringify(opts));
}
};
};
}
t.STATEMENT_OR_BLOCK_KEYS = ["consequent", "body"];
@@ -22,14 +33,59 @@ t.STATEMENT_OR_BLOCK_KEYS = ["consequent", "body"];
t.VISITOR_KEYS = require("./visitor-keys");
_.each(t.VISITOR_KEYS, function (keys, type) {
var is = t["is" + type] = function (node, opts) {
return node && node.type === type && t.shallowEqual(node, opts);
};
t.ALIAS_KEYS = require("./alias-keys");
addAssert(type, is);
t.FLIPPED_ALIAS_KEYS = {};
_.each(t.VISITOR_KEYS, function (keys, type) {
registerType(type, true);
});
_.each(t.ALIAS_KEYS, function (aliases, type) {
_.each(aliases, function (alias) {
var types = t.FLIPPED_ALIAS_KEYS[alias] = t.FLIPPED_ALIAS_KEYS[alias] || [];
types.push(type);
});
});
_.each(t.FLIPPED_ALIAS_KEYS, function (types, type) {
t[type.toUpperCase() + "_TYPES"] = types;
registerType(type, false);
});
/**
* Returns whether `node` is of given `type`.
* For better performance, use this instead of `is[Type]` when `type` is unknown.
* Optionally, pass `skipAliasCheck` to directly compare `node.type` with `type`.
*
* @param {String} type
* @param {Node} node
* @param {Object?} opts
* @param {Boolean?} skipAliasCheck
* @returns {Boolean} isOfType
*/
t.is = function (type, node, opts, skipAliasCheck) {
if (!node) return;
var typeMatches = (type === node.type);
if (!typeMatches && !skipAliasCheck) {
var aliases = t.FLIPPED_ALIAS_KEYS[type];
if (typeof aliases !== 'undefined')
typeMatches = aliases.indexOf(node.type) > -1;
}
if (!typeMatches) {
return false;
}
if (typeof opts !== 'undefined')
return t.shallowEqual(node, opts);
return true;
};
//
t.BUILDER_KEYS = _.defaults(require("./builder-keys"), t.VISITOR_KEYS);
@@ -45,29 +101,6 @@ _.each(t.BUILDER_KEYS, function (keys, type) {
};
});
//
t.ALIAS_KEYS = require("./alias-keys");
t.FLIPPED_ALIAS_KEYS = {};
_.each(t.ALIAS_KEYS, function (aliases, type) {
_.each(aliases, function (alias) {
var types = t.FLIPPED_ALIAS_KEYS[alias] = t.FLIPPED_ALIAS_KEYS[alias] || [];
types.push(type);
});
});
_.each(t.FLIPPED_ALIAS_KEYS, function (types, type) {
t[type.toUpperCase() + "_TYPES"] = types;
var is = t["is" + type] = function (node, opts) {
return node && types.indexOf(node.type) >= 0 && t.shallowEqual(node, opts);
};
addAssert(type, is);
});
/**
* Description
*
@@ -139,17 +172,17 @@ t.toSequenceExpression = function (nodes, scope) {
//
t.shallowEqual = function (actual, expected) {
var same = true;
var keys = Object.keys(expected);
var key;
if (expected) {
_.each(expected, function (val, key) {
if (actual[key] !== val) {
return same = false;
}
});
for (var i = 0; i < keys.length; i++) {
key = keys[i];
if (actual[key] !== expected[key])
return false;
}
return same;
return true;
};
/**
@@ -193,6 +226,21 @@ t.isReferenced = function (node, parent) {
// we're a property key and we aren't computed so we aren't referenced
if (t.isProperty(parent) && parent.key === node && !parent.computed) return false;
if (t.isFunction(parent)) {
// we're a function param
if (_.contains(parent.params, node)) return false;
// we're a rest parameter
if (parent.rest === node) return false;
}
if (t.isMethodDefinition(parent) && parent.key === node && !parent.computed) {
return false;
}
// we're a catch clause param
if (t.isCatchClause(parent) && parent.param === node) return false;
// we're a variable declarator id so we aren't referenced
if (t.isVariableDeclarator(parent) && parent.id === node) return false;
@@ -307,6 +355,31 @@ t.toStatement = function (node, ignore) {
return node;
};
/**
* Description
*
* @param {Object} node
* @returns {Object}
*/
exports.toExpression = function (node) {
if (t.isExpressionStatement(node)) {
node = node.expression;
}
if (t.isClass(node)) {
node.type = "ClassExpression";
} else if (t.isFunction(node)) {
node.type = "FunctionExpression";
}
if (t.isExpression(node)) {
return node;
} else {
throw new Error("cannot turn " + node.type + " to an expression");
}
};
/**
* Description
*
@@ -320,7 +393,11 @@ t.toBlock = function (node, parent) {
return node;
}
if (!_.isArray(node)) {
if (t.isEmptyStatement(node)) {
node = [];
}
if (!Array.isArray(node)) {
if (!t.isStatement(node)) {
if (t.isFunction(parent)) {
node = t.returnStatement(node);
@@ -363,7 +440,7 @@ t.getIds = function (node, map, ignoreTypes) {
if (t.isIdentifier(id)) {
ids[id.name] = id;
} else if (nodeKeys) {
for (i in nodeKeys) {
for (i = 0; i < nodeKeys.length; i++) {
key = nodeKeys[i];
if (id[key]) {
search.push(id[key]);
@@ -371,7 +448,7 @@ t.getIds = function (node, map, ignoreTypes) {
}
}
} else if (arrKeys) {
for (i in arrKeys) {
for (i = 0; i < arrKeys.length; i++) {
key = arrKeys[i];
search = search.concat(id[key] || []);
}

View File

@@ -12,11 +12,13 @@ var _ = require("lodash");
exports.inherits = util.inherits;
exports.canCompile = function (filename, altExts) {
var exts = altExts || [".js", ".jsx", ".es6", ".es"];
var exts = altExts || exports.canCompile.EXTENSIONS;
var ext = path.extname(filename);
return _.contains(exts, ext);
};
exports.canCompile.EXTENSIONS = [".js", ".jsx", ".es6", ".es"];
exports.isInteger = function (i) {
return _.isNumber(i) && i % 1 === 0;
};
@@ -39,7 +41,7 @@ exports.list = function (val) {
exports.regexify = function (val) {
if (!val) return new RegExp(/.^/);
if (_.isArray(val)) val = val.join("|");
if (Array.isArray(val)) val = val.join("|");
if (_.isString(val)) return new RegExp(val);
if (_.isRegExp(val)) return val;
throw new TypeError("illegal type for regexify");
@@ -48,7 +50,7 @@ exports.regexify = function (val) {
exports.arrayify = function (val) {
if (!val) return [];
if (_.isString(val)) return exports.list(val);
if (_.isArray(val)) return val;
if (Array.isArray(val)) return val;
throw new TypeError("illegal type for arrayify");
};
@@ -65,12 +67,12 @@ exports.sourceMapToComment = function (map) {
return "//# sourceMappingURL=data:application/json;base64," + base64;
};
exports.pushMutatorMap = function (mutatorMap, key, kind, method) {
exports.pushMutatorMap = function (mutatorMap, key, kind, computed, method) {
var alias;
if (t.isIdentifier(key)) {
alias = key.name;
if (method.computed) alias = "computed:" + alias;
if (computed) alias = "computed:" + alias;
} else if (t.isLiteral(key)) {
alias = String(key.value);
} else {
@@ -86,7 +88,7 @@ exports.pushMutatorMap = function (mutatorMap, key, kind, method) {
mutatorMap[alias] = map;
map._key = key;
if (method.computed) {
if (computed) {
map._computed = true;
}
@@ -101,7 +103,12 @@ exports.buildDefineProperties = function (mutatorMap) {
var propNode = t.property("init", map._key, mapNode, map._computed);
if (!map.get && !map.set) {
map.writable = t.literal(true);
}
map.enumerable = t.literal(true);
map.configurable = t.literal(true);
_.each(map, function (node, key) {
if (key[0] === "_") return;
@@ -188,7 +195,13 @@ exports.codeFrame = function (lines, lineNumber, colNumber) {
exports.repeat = function (width, cha) {
cha = cha || " ";
return new Array(width + 1).join(cha);
var result = "";
for (var i = 0; i < width; i++) {
result += cha;
}
return result;
};
exports.normaliseAst = function (ast, comments, tokens) {
@@ -256,7 +269,7 @@ var loadTemplates = function () {
if (!fs.existsSync(templatesLoc)) {
throw new Error("no templates directory - this is most likely the " +
"result of a broken `npm publish`. Please report to " +
"https://githut.com/6to5/6to5/issues");
"https://github.com/6to5/6to5/issues");
}
_.each(fs.readdirSync(templatesLoc), function (name) {

View File

@@ -1,16 +1,10 @@
{
"name": "6to5",
"description": "Turn ES6 code into readable vanilla ES5 with source maps",
"version": "2.7.3",
"version": "2.12.5",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://github.com/6to5/6to5",
"repository": {
"type": "git",
"url": "https://github.com/6to5/6to5.git"
},
"bugs": {
"url": "https://github.com/6to5/6to5/issues"
},
"homepage": "https://6to5.org/",
"repository": "6to5/6to5",
"preferGlobal": true,
"main": "lib/6to5/index.js",
"bin": {
@@ -39,36 +33,36 @@
"test": "make test"
},
"dependencies": {
"acorn-6to5": "0.11.1-11",
"acorn-6to5": "0.11.1-16",
"ast-types": "~0.6.1",
"chokidar": "0.11.1",
"commander": "2.5.0",
"core-js": "^0.4.1",
"core-js": "0.4.4",
"estraverse": "1.8.0",
"esutils": "1.1.6",
"esvalid": "^1.1.0",
"esvalid": "1.1.0",
"fs-readdir-recursive": "0.1.0",
"jshint": "^2.5.10",
"jshint": "2.5.10",
"lodash": "2.4.1",
"mkdirp": "0.5.0",
"output-file-sync": "^1.1.0",
"private": "0.1.6",
"regenerator": "^0.8.3",
"regenerator": "0.8.3",
"regexpu": "0.3.0",
"roadrunner": "^1.0.4",
"roadrunner": "1.0.4",
"source-map": "0.1.40",
"source-map-support": "0.2.8"
},
"devDependencies": {
"browserify": "6.3.2",
"chai": "^1.9.2",
"chai": "1.9.2",
"istanbul": "0.3.2",
"jshint-stylish": "^1.0.0",
"jshint-stylish": "1.0.0",
"matcha": "0.6.0",
"mocha": "1.21.4",
"rimraf": "2.2.8",
"uglify-js": "2.4.15"
},
"optionalDependencies": {
"kexec": "^0.2.0"
"kexec": "0.2.0"
}
}

View File

@@ -1,16 +1,15 @@
// skip these tests under instanbul since they're useless
if (process.env.running_under_istanbul === '1') return;
if (process.env.running_under_istanbul) return;
var readdir = require("fs-readdir-recursive");
var helper = require("./_helper");
var assert = require("assert");
var rimraf = require("rimraf");
var mkdirp = require("mkdirp");
var child = require("child_process");
var path = require("path");
var chai = require("chai");
var fs = require("fs");
var _ = require("lodash");
var readdir = require("fs-readdir-recursive");
var helper = require("./_helper");
var assert = require("assert");
var rimraf = require("rimraf");
var outputFileSync = require("output-file-sync");
var child = require("child_process");
var path = require("path");
var chai = require("chai");
var fs = require("fs");
var _ = require("lodash");
var fixtureLoc = __dirname + "/fixtures/bin";
var tmpLoc = __dirname + "/tmp";
@@ -28,10 +27,7 @@ var readDir = function (loc) {
var saveInFiles = function (files) {
_.each(files, function (content, filename) {
var up = path.normalize(filename + "/..");
mkdirp.sync(up);
fs.writeFileSync(filename, content);
outputFileSync(filename, content);
});
};

View File

@@ -12,7 +12,7 @@ suite("browserify", function() {
assert.ok(bundle.length, "bundle output code");
// ensure that the code runs without throwing an exception
vm.runInNewContext(bundle, {});
vm.runInNewContext("var global = this;\n" + bundle, {});
done();
})
})

View File

@@ -1,5 +1,3 @@
if (!process.env.ALL_6TO5_TESTS) return;
require("./_transformation-helper")({
name: "esnext"
});

View File

@@ -1,9 +1,11 @@
class Animal {
class Base {
get sound() {
return 'I am a ' + this.type + '.';
}
}
class Animal extends Base {}
class Cat extends Animal {
get type() { return 'cat'; }

View File

@@ -7,4 +7,5 @@ var test = {
* Inside bracket init
*/
"b"]: "2"
}, ok = 42;
},
ok = 42;

View File

@@ -3,6 +3,7 @@ function test() {
// Leading to VariableDeclarator
// Leading to VariableDeclarator
i = 20,
// Leading to VariableDeclarator
// Leading to VariableDeclarator
j = 20;

View File

@@ -5,6 +5,7 @@ function test() {
* Leading to VariableDeclarator
*/
i = 20,
/*
* Leading to VariableDeclarator
* Leading to VariableDeclarator

View File

@@ -1,5 +1,6 @@
function* foo() {
var a = yield wat(), b = 2;
var a = yield wat(),
b = 2;
var c = yield a = b;
yield a, yield b;
yield a = b;

View File

@@ -1,2 +1,3 @@
++i;
i++;
(foo++).test();

View File

@@ -1,2 +1,3 @@
++i;
i++;
(foo++).test();

View File

@@ -8,6 +8,9 @@ const foo = "foo";
let foo, bar = "bar";
var foo, bar = "bar";
let foo = "foo", bar = "bar";
var foo = "foo", bar = "bar";
const foo = "foo", bar = "bar";
let foo = "foo",
bar = "bar";
var foo = "foo",
bar = "bar";
const foo = "foo",
bar = "bar";

View File

@@ -0,0 +1,25 @@
class Test extends Foo {
constructor() {
woops.super.test();
super();
super.test();
super(...arguments);
super("test", ...arguments);
super.test(...arguments);
super.test("test", ...arguments);
}
test() {
super();
super(...arguments);
super("test", ...arguments);
}
static foo() {
super();
super(...arguments);
super("test", ...arguments);
}
}

View File

@@ -0,0 +1,50 @@
"use strict";
var _slice = Array.prototype.slice;
var _inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) subClass.__proto__ = superClass;
};
var Test = (function (Foo) {
function Test() {
var _Foo$prototype$test, _Foo$prototype$test2;
woops["super"].test();
Foo.call(this);
Foo.prototype.test.call(this);
Foo.call.apply(Foo, [this].concat(_slice.call(arguments)));
Foo.call.apply(Foo, [this, "test"].concat(_slice.call(arguments)));
(_Foo$prototype$test = Foo.prototype.test).call.apply(_Foo$prototype$test, [this].concat(_slice.call(arguments)));
(_Foo$prototype$test2 = Foo.prototype.test).call.apply(_Foo$prototype$test2, [this, "test"].concat(_slice.call(arguments)));
}
_inherits(Test, Foo);
Test.prototype.test = function test() {
var _Foo$prototype$test3, _Foo$prototype$test4;
Foo.prototype.test.call(this);
(_Foo$prototype$test3 = Foo.prototype.test).call.apply(_Foo$prototype$test3, [this].concat(_slice.call(arguments)));
(_Foo$prototype$test4 = Foo.prototype.test).call.apply(_Foo$prototype$test4, [this, "test"].concat(_slice.call(arguments)));
};
Test.foo = function foo() {
var _Foo$foo, _Foo$foo2;
Foo.foo.call(this);
(_Foo$foo = Foo.foo).call.apply(_Foo$foo, [this].concat(_slice.call(arguments)));
(_Foo$foo2 = Foo.foo).call.apply(_Foo$foo2, [this, "test"].concat(_slice.call(arguments)));
};
return Test;
})(Foo);

View File

@@ -0,0 +1,6 @@
class Test extends Foo {
constructor() {
super.test;
super.test.whatever;
}
}

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