Compare commits

...

367 Commits

Author SHA1 Message Date
Sebastian McKenzie
f3dfe9571e v3.0.1 2015-01-28 13:17:34 +11:00
Sebastian McKenzie
9b9e2c4ac0 remove iojs from travis 2015-01-28 13:15:45 +11:00
Sebastian McKenzie
28e0b17a81 3.0.0 2015-01-28 13:14:05 +11:00
Sebastian McKenzie
b02f10053e fix publish-runtime task 2015-01-28 13:14:00 +11:00
Sebastian McKenzie
979dcd5330 downgrade kexec 2015-01-28 13:13:52 +11:00
Sebastian McKenzie
ff18fd37df v3.0.0 2015-01-28 13:08:55 +11:00
Sebastian McKenzie
dd56d53556 fix linting errors 2015-01-28 13:06:21 +11:00
Sebastian McKenzie
2b85045b61 split up class expressions in export default 2015-01-28 12:58:05 +11:00
Sebastian McKenzie
a1e11aba61 make explode assignable expression helper aware of declared variables so we can simplify code a lot and drop the variable declaration as evaluating it multiple times has no consequence 2015-01-28 11:50:14 +11:00
Sebastian McKenzie
946ba7a8d3 add iojs to travis 2015-01-28 11:03:00 +11:00
Sebastian McKenzie
4a94ef3aa6 add syntax highlighting to syntax error code frames 2015-01-28 11:02:54 +11:00
Sebastian McKenzie
fd45e9218c Merge branch 'master' into 3.0.0
Conflicts:
	package.json
2015-01-27 20:52:45 +11:00
Sebastian McKenzie
24d4d6d73a remove esModule flag from systemjs module formatter - fixes #599 2015-01-27 20:40:43 +11:00
Sebastian McKenzie
47b56d089f upgrade jshint and kexec 2015-01-27 07:38:14 +11:00
Sebastian McKenzie
10ede7c934 fix extends helper checking the wrong object - thanks @appden! 2015-01-27 07:38:08 +11:00
Sebastian McKenzie
344390d1b5 fix simple tests - @thejameskyle 2015-01-27 07:18:21 +11:00
Sebastian McKenzie
2869878046 use hasOwnProperty in extends helper 2015-01-27 07:16:57 +11:00
Sebastian McKenzie
2f79bee367 use either print or eval in 6to5-node - closes #591 2015-01-27 07:07:05 +11:00
Sebastian McKenzie
202d98c318 fix linting errors 2015-01-27 07:06:12 +11:00
Sebastian McKenzie
442a39359e Merge pull request #595 from 6to5/lodash
Lodash 3.0 & Regexpu 1.1
2015-01-27 06:47:55 +11:00
James Kyle
c907f8703a Fix regex transpilation test for regexpu 1.1 2015-01-26 11:44:18 -08:00
Sebastian McKenzie
6f2925ed83 remove React.__spread and use extends helper instead - fixes #594 2015-01-27 06:43:57 +11:00
Sebastian McKenzie
f256e18182 add -L arg to loose in the CLI 2015-01-27 06:40:57 +11:00
James Kyle
f9521e5599 Bump Lodash to 3.0 2015-01-26 11:39:01 -08:00
Sebastian McKenzie
41ae06f1aa Merge pull request #593 from jhorwit2/master
Upgrade core-js dependency to fix firefox issue
2015-01-27 06:34:59 +11:00
Josh Horwitz
e5613e9e0d Merge pull request #1 from jhorwit2/jhorwit2-patch-1
Updated minor version upgrade of corejs to fix firefox 20-23 issue
2015-01-26 13:38:32 -05:00
Josh Horwitz
779d14311a Updated minor version upgrade of corejs to fix firefox 20-23 issue 2015-01-26 13:38:09 -05:00
Sebastian McKenzie
971da50129 add a transformer pass class 2015-01-26 22:10:19 +11:00
Sebastian McKenzie
c49438da60 add namespaces and better structure transformation 2015-01-26 21:10:05 +11:00
Sebastian McKenzie
e4a030c916 upgrade acorn-6to5 2015-01-26 20:30:53 +11:00
Sebastian McKenzie
c72f9d894d only use GeneratorBuffer::space if it's for pretty printing so we can drop all spaces easily 2015-01-26 18:13:39 +11:00
Sebastian McKenzie
59283c1148 clean up traversal some more to make it clearer 2015-01-26 18:13:21 +11:00
Sebastian McKenzie
cfe9a4e270 add isConsequenceExpressionStatement last 2015-01-26 17:43:19 +11:00
Sebastian McKenzie
0110d18d4c clearn up traversal and fix replacement node arrays not being traversed - fixes #589 2015-01-26 17:43:11 +11:00
Sebastian McKenzie
2bd1afc5fd fix up traverse tests 2015-01-26 17:08:40 +11:00
Sebastian McKenzie
6875277375 upgrade acorn-6to5 2015-01-26 17:00:34 +11:00
Sebastian McKenzie
9b5045bb91 revert back to simpler osx-only test browser opening 2015-01-26 17:00:28 +11:00
Sebastian McKenzie
f14c0fa5d6 turn off failed test writes 2015-01-26 17:00:19 +11:00
Sebastian McKenzie
4b6203d1f4 simplify class default exports 2015-01-26 16:00:30 +11:00
Sebastian McKenzie
3db7811f00 add missing use strict declarations 2015-01-26 15:53:24 +11:00
Sebastian McKenzie
8243a34b69 change the way modules handle default exports and function declaration exports 2015-01-26 15:53:17 +11:00
Sebastian McKenzie
a821b2249b add class tests to optional async transformers 2015-01-26 15:52:39 +11:00
Sebastian McKenzie
0a851ced19 remove runtime option 2015-01-26 15:52:23 +11:00
Sebastian McKenzie
a2a1ab4c52 clean up file 2015-01-26 13:51:33 +11:00
Sebastian McKenzie
876d88c761 fix module specifier default output 2015-01-26 13:51:27 +11:00
Sebastian McKenzie
d473826a68 add window and self to valid global keys 2015-01-26 13:51:15 +11:00
Sebastian McKenzie
cfd0059fc7 fix linting errors 2015-01-26 13:51:06 +11:00
Sebastian McKenzie
b21b0e753e add back optional brackets around transformers in 6to5 --help 2015-01-26 13:50:44 +11:00
Sebastian McKenzie
5253502846 upgrade acorn-6to5 2015-01-26 12:02:58 +11:00
Sebastian McKenzie
526e743c58 fix 6to5-node blacklist 2015-01-26 12:01:03 +11:00
Sebastian McKenzie
7df0d0530f update 3.0.0 changelog 2015-01-26 11:49:05 +11:00
Sebastian McKenzie
567479787b update tests to reflect new helper compact behaviour 2015-01-26 11:48:35 +11:00
Sebastian McKenzie
59e3eb2bd1 move doDefaultExportInterop to default module formatter 2015-01-26 11:43:46 +11:00
Sebastian McKenzie
b449dbe891 make helpers compact/no newlines/comments 2015-01-26 11:43:34 +11:00
Sebastian McKenzie
c7c99efa8e add back strict module formatters 2015-01-26 10:57:06 +11:00
Sebastian McKenzie
2808bc2c90 add in custom acorn node constructor 2015-01-26 01:32:37 +11:00
Sebastian McKenzie
9b7eb2dcd8 update 3.0.0 changelog 2015-01-26 00:14:35 +11:00
Sebastian McKenzie
274b58573b change -l whitelist flag to -w in bin/6to5-node 2015-01-26 00:14:19 +11:00
Sebastian McKenzie
d7f33121c9 upgrade acorn-6to5 2015-01-26 00:14:08 +11:00
Sebastian McKenzie
75460b91d8 clean up module formatters and fix interopRequireWildcard helper 2015-01-26 00:14:04 +11:00
Sebastian McKenzie
3d355566dc avoid duplicate requires when importing modules 2015-01-25 20:39:41 +11:00
Sebastian McKenzie
a3b58edc52 only remap break/continue when inside a loop 2015-01-25 18:46:20 +11:00
Sebastian McKenzie
5c71b1a031 add base for naughty polyfill tool 2015-01-25 18:46:04 +11:00
Sebastian McKenzie
585e21a734 add whitelist and blacklist options to 6to5-node - closes #588 2015-01-25 17:26:51 +11:00
Sebastian McKenzie
a46f4f7873 upgrade acorn-6to5 2015-01-25 17:23:34 +11:00
Sebastian McKenzie
456bce1c9a rename loose modules 2015-01-25 15:46:27 +11:00
Sebastian McKenzie
d8046333c0 add test location to ast validation 2015-01-25 15:46:17 +11:00
Sebastian McKenzie
49c28d449e deprecate old transformer names 2015-01-25 15:46:04 +11:00
Sebastian McKenzie
3fdf492dcf safer common interop - closes #493 2015-01-25 14:03:25 +11:00
Sebastian McKenzie
99a4343626 use clone helper instead of lodash cloneDeep - fixes #583 2015-01-24 16:32:55 +11:00
Sebastian McKenzie
8eb3091a9d update params generator to work with new parameters 2015-01-24 16:32:37 +11:00
Sebastian McKenzie
befa221bd9 only get the basename for task names in test helper 2015-01-24 16:32:17 +11:00
Sebastian McKenzie
a954ae3a6e add breaking switch break test 2015-01-24 16:32:02 +11:00
Sebastian McKenzie
afa0a31b91 add no loopParent warning to block scoping transformer 2015-01-24 16:31:52 +11:00
Sebastian McKenzie
8a13c12738 switch rest and default parameters to new ast type 2015-01-24 16:31:43 +11:00
Sebastian McKenzie
b938e1aece rename misc transformers 2015-01-24 15:20:23 +11:00
Sebastian McKenzie
89a3206553 Merge branch 'master' into 3.0.0
Conflicts:
	CHANGELOG.md
	lib/6to5/transformation/transformers/optional-core-aliasing.js
2015-01-24 15:00:44 +11:00
Sebastian McKenzie
66e9df6b0b v2.13.7 2015-01-24 11:44:08 +11:00
Sebastian McKenzie
2fb299da22 update 2.13.7 changelog 2015-01-24 11:40:26 +11:00
Sebastian McKenzie
23d962b838 Revert "move optional async transformers down - fixes #580"
This reverts commit 9cf1c62147.
2015-01-24 11:39:50 +11:00
Sebastian McKenzie
519454c343 don't realias variables that are already declared in optional coreAliasing transformer - fixes #579 2015-01-24 11:26:51 +11:00
Sebastian McKenzie
9cf1c62147 move optional async transformers down - fixes #580 2015-01-24 11:20:56 +11:00
Sebastian McKenzie
0e6bd3ed08 v2.13.6 2015-01-24 11:13:59 +11:00
Sebastian McKenzie
95a3a02469 disable failing let scoping test 2015-01-24 11:10:18 +11:00
Sebastian McKenzie
1a0cad2ac1 add new expression as a valid conditional expression parent for parantheses insertion - fixes #578 2015-01-24 10:29:34 +11:00
Sebastian McKenzie
d78a01086d add new expression as a valid conditional expression parent for parantheses insertion - fixes #578 2015-01-24 10:29:12 +11:00
Sebastian McKenzie
3607689fbc fix tests to reflect new destructuring statement behaviour 2015-01-24 00:23:15 +11:00
Sebastian McKenzie
70ce6e0ab8 update 3.0.0 changelog 2015-01-24 00:21:21 +11:00
Sebastian McKenzie
914ef4c5f5 remove 6to5-node repl console.log 2015-01-24 00:21:15 +11:00
Sebastian McKenzie
75389b04a6 use isConsequenceExpressionStatement to correctly evaluate expressions - fixes #502 2015-01-24 00:19:48 +11:00
Sebastian McKenzie
3167d66154 add t.getLastStatements and File::isConsequenceExpressionStatement 2015-01-24 00:04:20 +11:00
Sebastian McKenzie
bd789ff032 fix bin/6to5 blacklist test 2015-01-24 00:03:32 +11:00
Sebastian McKenzie
c118c10a9d update 3.0.0 changelog 2015-01-23 23:47:16 +11:00
Sebastian McKenzie
8ed1325dfc fix RestElement argument type 2015-01-23 23:47:02 +11:00
Sebastian McKenzie
33cd9eeafd don't hoist regenerator variable declarations in system module formatter 2015-01-23 23:46:43 +11:00
Sebastian McKenzie
b280303a10 remove register opts 2015-01-23 23:46:27 +11:00
Sebastian McKenzie
0ad071af4e upgrade acorn-6to5 2015-01-23 23:46:20 +11:00
Sebastian McKenzie
a22cd72440 update to RestElement - @RReverser 2015-01-23 23:20:45 +11:00
Sebastian McKenzie
4fee58e7bc remove includeRegenerator option 2015-01-23 23:05:35 +11:00
Sebastian McKenzie
86b6904e77 fix esnext tests to reflect new super behaviour 2015-01-23 23:05:24 +11:00
Sebastian McKenzie
9f435d02f2 switch to a custom list of global keys and use object helper 2015-01-23 23:04:33 +11:00
Sebastian McKenzie
5419616063 remove optional prefixing 2015-01-23 23:03:49 +11:00
Sebastian McKenzie
5f8f9e35d7 better categorisation of transformers 2015-01-23 23:03:41 +11:00
Sebastian McKenzie
e1d2def4b1 add t.getSpecifierId that handles default specifiers 2015-01-23 23:03:04 +11:00
Sebastian McKenzie
36fef5676a add helpers 2015-01-23 23:02:48 +11:00
Sebastian McKenzie
063fec0ca6 better categorisation of transformers 2015-01-23 23:02:40 +11:00
Sebastian McKenzie
c7e4213641 update 3.0.0 changelog 2015-01-23 09:39:47 +11:00
Sebastian McKenzie
bff150f69d fix filenameRelative name and remove amdModuleIds 2015-01-23 09:39:42 +11:00
Sebastian McKenzie
dc209417e7 move internal tools from bin to tools 2015-01-23 09:39:22 +11:00
Sebastian McKenzie
fb74832594 update 3.0.0 changelog 2015-01-23 09:26:33 +11:00
Sebastian McKenzie
49cd1753e6 throw on unknown options 2015-01-23 09:26:27 +11:00
Sebastian McKenzie
36fa887be8 update XJS namespaces to JSX 2015-01-23 08:08:56 +11:00
Sebastian McKenzie
dacb187f11 upgrade acorn-6to5 2015-01-23 08:08:47 +11:00
Sebastian McKenzie
5815b17dee Merge branch 'master' into 3.0.0 2015-01-23 07:12:28 +11:00
Sebastian McKenzie
fe594dfe0c Merge pull request #572 from assaf/master
Added test case for issue #564
2015-01-23 07:12:02 +11:00
Assaf Arkin
4fe6ad43c1 Added test case for issue #564 2015-01-22 10:19:45 -08:00
Sebastian McKenzie
377212290f 6to5/polyfill can now only be required **once** 2015-01-23 00:19:30 +11:00
Sebastian McKenzie
51b6946a98 remove unlink event watching in bin/6to5 2015-01-23 00:19:19 +11:00
Sebastian McKenzie
c90904a139 put 3.0.0 changes into subsections 2015-01-22 19:24:04 +11:00
Sebastian McKenzie
8f68f62f8a add jscs 2015-01-22 19:23:56 +11:00
Sebastian McKenzie
8678917e2a add util.object that we'll use to construct objects to avoid prototype collisions 2015-01-22 18:39:31 +11:00
Sebastian McKenzie
115509653f remove strict module transformers 2015-01-22 18:39:09 +11:00
Sebastian McKenzie
f43fc08a8f remove indent option from cli 2015-01-22 18:38:21 +11:00
Sebastian McKenzie
31504a5187 add async to generator helper update note 2015-01-22 17:20:38 +11:00
Sebastian McKenzie
9bfe6e7aac add Scope::getFunctionParent method 2015-01-22 17:20:29 +11:00
Sebastian McKenzie
2e0a185db6 keep function id location in block scoped function transformer 2015-01-22 17:20:19 +11:00
Sebastian McKenzie
f63ce4ddd4 rename _letDeclars to _letDeclarators in es6 block scoping transformer 2015-01-22 17:20:05 +11:00
Sebastian McKenzie
c4fb5a5e40 more compact async to generator helper 2015-01-22 17:19:22 +11:00
Sebastian McKenzie
738203485c Merge pull request #569 from caspervonb/makefile-open
Use $BROWSER with fallbacks for opening browser tests
2015-01-22 16:05:56 +11:00
Casper Beyer
5218d07b0d Use $BROWSER with fallbacks for opening browser tests 2015-01-22 12:45:47 +08:00
Sebastian McKenzie
b9b1a44c28 support async await inside of let scoping closure wrapper - fixes #565 2015-01-22 10:53:05 +11:00
Sebastian McKenzie
c0a4e7ad55 upgrade core-js to 0.4.6 2015-01-22 10:12:24 +11:00
Sebastian McKenzie
9ed8e4a35b remove names from optional async tests 2015-01-22 10:12:11 +11:00
Sebastian McKenzie
3e2d611707 store all undeclared references on Program to better handle let scoping 2015-01-22 10:12:03 +11:00
Sebastian McKenzie
5463872926 optional async transformers should remove their ids - fixes #552 2015-01-22 08:15:35 +11:00
Sebastian McKenzie
81ff635c60 fix tests to reflect new super behaviour 2015-01-22 08:07:59 +11:00
Sebastian McKenzie
7072f64397 remove debug console.log 2015-01-22 08:07:37 +11:00
Sebastian McKenzie
418de75e77 fix bare super call being illegal in non-constructors 2015-01-22 07:54:01 +11:00
Sebastian McKenzie
bed2826e3b update 3.0.0 changelog 2015-01-22 07:52:36 +11:00
Sebastian McKenzie
f2a432531e make bare super call in non-constructors illegal 2015-01-22 07:52:31 +11:00
Sebastian McKenzie
da6c2b8d6a add illegal top level this transformer - fixes #562 2015-01-22 07:44:36 +11:00
Sebastian McKenzie
b02e28f3fd add additional 3.0.0 change notes 2015-01-22 07:38:08 +11:00
Sebastian McKenzie
da8888a350 move around transformers to work better with regenerator 2015-01-22 07:37:59 +11:00
Sebastian McKenzie
43856136d5 update tests 2015-01-22 07:37:45 +11:00
Sebastian McKenzie
589d20019f bump regenerator 2015-01-22 07:37:37 +11:00
Sebastian McKenzie
50d3599f76 upgrade regenerator-6to5 2015-01-22 07:37:26 +11:00
Sebastian McKenzie
870954c6be rewrite constants transformer 2015-01-22 07:37:18 +11:00
Sebastian McKenzie
6959e60e2c bump 6to5-runtime version 2015-01-22 01:47:19 +11:00
Sebastian McKenzie
9cdbb99eb9 fix linting errors 2015-01-22 01:47:13 +11:00
Sebastian McKenzie
48cebd5e30 rename es6.generators to regenerator 2015-01-22 01:47:07 +11:00
Sebastian McKenzie
4e829f3e1b categorise 3.0.0 changes 2015-01-22 01:46:33 +11:00
Sebastian McKenzie
7cbe914b22 update 3.0.0 changelog 2015-01-22 01:45:48 +11:00
Sebastian McKenzie
c2d61ad660 more intelligent scope tracking and insertion 2015-01-22 01:40:26 +11:00
Sebastian McKenzie
878a7ada06 better dynamic imports/data 2015-01-22 01:38:18 +11:00
Sebastian McKenzie
b7b2845160 add descriptions about why some transformers are in the position they are 2015-01-22 01:38:08 +11:00
Sebastian McKenzie
2ab4a3d362 update tests to reflect new uid behaviour 2015-01-22 01:37:50 +11:00
Sebastian McKenzie
cfd95a1398 only require imports that are necessary in selfContained 2015-01-22 01:37:28 +11:00
Sebastian McKenzie
ccdb480d44 rename traverser to visitor 2015-01-22 00:28:20 +11:00
Sebastian McKenzie
ac373a9e1c use scope for uid registry instead of a global registry 2015-01-22 00:27:45 +11:00
Sebastian McKenzie
4ce7d5a5b4 Merge branch 'guybedford-system-tests' into 3.0.0 2015-01-21 23:59:41 +11:00
Sebastian McKenzie
1e217c745b Merge branch 'system-tests' of https://github.com/guybedford/6to5 into guybedford-system-tests 2015-01-21 23:59:32 +11:00
Sebastian McKenzie
287bfc77b2 add scope file.generateUidIdentifier alias 2015-01-21 23:58:43 +11:00
Sebastian McKenzie
3205c78f01 ensure that a scope is always passed to traverse and allow scopes to have access to file 2015-01-21 23:52:12 +11:00
Sebastian McKenzie
0b6d49e421 better handling of optional transformers 2015-01-21 23:34:18 +11:00
Sebastian McKenzie
546a44d1d7 autoindentation - fixes #467 2015-01-21 23:33:57 +11:00
Sebastian McKenzie
ac891bebaa nicer unknown transformer message 2015-01-21 23:33:30 +11:00
Sebastian McKenzie
0ab4326026 Merge branch 'gaearon-traversers-3.0.0' into 3.0.0 2015-01-21 23:13:51 +11:00
Sebastian McKenzie
5fcfff23a4 Merge branch 'traversers-3.0.0' of https://github.com/gaearon/6to5 into gaearon-traversers-3.0.0 2015-01-21 23:13:43 +11:00
Sebastian McKenzie
28fe45bd1d namespace all transformer keys with their type 2015-01-21 23:12:57 +11:00
Sebastian McKenzie
f312026c23 move transformers into their corresponding type folder 2015-01-21 23:04:31 +11:00
guybedford
8023788305 add generator and variable binding tests 2015-01-21 13:58:49 +02:00
Sebastian McKenzie
0d0d89fd9c better names for property transformers 2015-01-21 22:41:55 +11:00
Sebastian McKenzie
019f2ee932 namespace default/rest parameter transformers 2015-01-21 22:40:50 +11:00
Sebastian McKenzie
8558505b65 merge comprehension transformers 2015-01-21 22:40:26 +11:00
Sebastian McKenzie
c51f8c48b6 rename let scoping transformer to block scoping 2015-01-21 22:40:17 +11:00
Dan Abramov
3d9d842a0d Extract traversers outside methods 2015-01-21 14:34:47 +03:00
Sebastian McKenzie
cfd028288f Merge branch 'master' into 3.0.0
Conflicts:
	CHANGELOG.md
	lib/6to5/transformation/transform.js
2015-01-21 17:56:34 +11:00
Sebastian McKenzie
194c080c64 v2.13.5 2015-01-21 13:37:06 +11:00
Sebastian McKenzie
4c6076e529 add 2.13.5 changelog 2015-01-21 13:35:30 +11:00
Sebastian McKenzie
df65ec08a2 support destructuring patterns in rest parameters - fixes #550 2015-01-21 13:35:24 +11:00
Sebastian McKenzie
62f11011b0 upgrade kexec - closes #551 2015-01-21 13:19:24 +11:00
Sebastian McKenzie
9385c7e4ad v2.13.4 2015-01-21 10:27:35 +11:00
Sebastian McKenzie
3c06e68cae fix default parameter node variable name 2015-01-21 10:21:27 +11:00
Sebastian McKenzie
e8810f5124 add 2.13.4 changelog 2015-01-21 10:20:13 +11:00
Sebastian McKenzie
3c258c4716 add proper ordering to function param logic - fixes #549 2015-01-21 10:17:52 +11:00
Sebastian McKenzie
193a3c167e loops should contain their child block let declarations 2015-01-20 19:33:26 +11:00
Sebastian McKenzie
4b525daf72 fix forOf scope declarations not propagating to new for loop - fixes #538 2015-01-20 19:33:05 +11:00
Sebastian McKenzie
e46f42872a add array comprehension collision test #538 2015-01-20 16:52:11 +11:00
Sebastian McKenzie
4790e4068a add for collision test #538 2015-01-20 16:52:00 +11:00
Sebastian McKenzie
26cb5d5a65 add block to for loop scope - fixes #538 2015-01-20 16:48:41 +11:00
Sebastian McKenzie
031bda61cc don't continue let scoping remapping if there are none to be remapped 2015-01-20 16:48:07 +11:00
Sebastian McKenzie
61f1fae83b remove unused template 2015-01-20 16:47:52 +11:00
Sebastian McKenzie
d911bdaf63 add AssignmentPattern support to scope tracking - fixes #537 2015-01-20 08:56:14 +11:00
Sebastian McKenzie
1859226e76 remove runtime test 2015-01-20 02:36:42 +11:00
Sebastian McKenzie
e4523de16d upgrade regenerator-6to5 2015-01-20 02:34:02 +11:00
Sebastian McKenzie
6a3829d605 remove includeRegenerator option 2015-01-20 02:31:19 +11:00
Sebastian McKenzie
437ba46889 update regenerator submodule url 2015-01-20 02:31:10 +11:00
Sebastian McKenzie
7007f7e0bb remove includeRegenerator option 2015-01-20 02:30:57 +11:00
Sebastian McKenzie
ff12a996de remove ALL check from regenerator tests 2015-01-20 02:30:49 +11:00
Sebastian McKenzie
faba02afd4 better block scoped functions 2015-01-20 02:30:41 +11:00
Sebastian McKenzie
5436e95c9a switch to regenerator-to5 2015-01-20 02:30:34 +11:00
Sebastian McKenzie
031099b58e add generator note to name method helper 2015-01-20 02:29:50 +11:00
Sebastian McKenzie
e75d1a1666 fix helper identifiers 2015-01-20 01:45:00 +11:00
Sebastian McKenzie
7f6eb3dba3 update selfContained transformer to use new File data layer 2015-01-20 01:42:43 +11:00
Sebastian McKenzie
33d2463c65 remove old runtime tests 2015-01-20 01:42:31 +11:00
Sebastian McKenzie
ab134d0919 add data abstraction layer to File 2015-01-20 01:36:00 +11:00
Sebastian McKenzie
d6412d0a1b Merge branch 'AluisioASG-scoped-es6-runtime' into 3.0.0 2015-01-20 01:34:50 +11:00
Sebastian McKenzie
9f41d6231e Merge branch 'scoped-es6-runtime' of https://github.com/AluisioASG/6to5 into AluisioASG-scoped-es6-runtime 2015-01-20 01:34:43 +11:00
Aluísio Augusto Silva Gonçalves
9d2e12dfa6 Amendments from 6to5/6to5#535 comments 2015-01-19 12:31:47 -02:00
Aluísio Augusto Silva Gonçalves
043bf13d24 Revert moving _blockHoist after regenerator
This reverts commits 81bec3e5c4 and
157f5c3304.
2015-01-19 12:24:54 -02:00
Aluísio Augusto Silva Gonçalves
3f96cf3963 Rename 6to5-runtime's helpers module to 'helpers' 2015-01-19 12:24:45 -02:00
Sebastian McKenzie
22fb346983 remove runtime option 2015-01-20 01:17:24 +11:00
Sebastian McKenzie
e7acfd7bb7 fix regenerator runtime build 2015-01-20 01:13:28 +11:00
Sebastian McKenzie
31cf740b99 fix regenerator location 2015-01-20 01:05:49 +11:00
Sebastian McKenzie
d75139a059 add 6to5-runtime build process #535 2015-01-20 00:56:09 +11:00
Sebastian McKenzie
7257e2445d Merge branch 'master' into 3.0.0
Conflicts:
	CHANGELOG.md
	lib/6to5/file.js
	lib/6to5/register.js
2015-01-20 00:36:06 +11:00
Sebastian McKenzie
f322252c36 add optional undeclared variable check transformer 2015-01-20 00:17:22 +11:00
Sebastian McKenzie
da16bf1e42 add t.isReferencedIdentifier 2015-01-20 00:17:11 +11:00
Aluísio Augusto Silva Gonçalves
157f5c3304 Remove regenerator edge case from selfContained test
Right now exporting a generator doesn't work because we hoist the
export assignment before the function expression assignment.  This
will be dealt with at another time as it is not specific to this
transformer.
2015-01-19 10:54:33 -02:00
Sebastian McKenzie
4a1addc558 better whitespace for VariableDeclarations 2015-01-19 22:09:05 +11:00
Aluísio Augusto Silva Gonçalves
e2bf61379f Add full-blown test for the selfContained transformer 2015-01-18 23:10:26 -02:00
Aluísio Augusto Silva Gonçalves
02019d4d8f Drop unnecessary dynamic import redeclaration in AMD
Instead of assigning the import a name and them declaring a new
variabled referencing that name, output the import already with
the destination name, since we know there must be no collisions
because these IDs are also generated.
2015-01-18 21:18:25 -02:00
Aluísio Augusto Silva Gonçalves
c81cc5cda0 Unify coreAliasing, externalRuntime and externalRegenerator
Merge all three transformers into the `selfContained` transformer,
as discussed in Gitter.  Name may not be final.
2015-01-18 21:15:30 -02:00
Aluísio Augusto Silva Gonçalves
8d288c01ca Import ES6 functions and helpers from 6to5-runtime
The new `6to5-runtime` packs core-js, 6to5's helpers and
the Regenerator runtime, and we're moving `coreAliasing`,
`externalRuntime` and `externalRegenerator` to use it
instead of forcing the user to depend on these packages
directly.
2015-01-18 20:39:35 -02:00
Sebastian McKenzie
857abf5024 v2.13.3 2015-01-19 09:05:37 +11:00
Sebastian McKenzie
6d67105bab add coverage and vendor to npmignore 2015-01-19 09:02:51 +11:00
Aluísio Augusto Silva Gonçalves
e2f4ca106e Merge branch 'external-regenerator-runtime' into scoped-es6-runtime 2015-01-18 20:02:48 -02:00
Aluísio Augusto Silva Gonçalves
061bbe0409 Merge branch 'external-runtime' into scoped-es6-runtime 2015-01-18 20:01:52 -02:00
Sebastian McKenzie
078b09676f v2.13.2 2015-01-19 09:00:15 +11:00
Sebastian McKenzie
b719eaf6ab add missing semicolon 2015-01-19 08:58:11 +11:00
Sebastian McKenzie
b63accca25 remove --mangle sort from uglify since it's causing issues in safari/ios 2015-01-19 08:57:43 +11:00
Sebastian McKenzie
2d41b09c3b add 2.12.3 changelog 2015-01-19 08:57:04 +11:00
Sebastian McKenzie
0b44137d1f exclude coverage folder from npm 2015-01-19 08:56:58 +11:00
Sebastian McKenzie
8d8dd5fa37 add let scoping transformer rename note 2015-01-19 08:54:26 +11:00
Sebastian McKenzie
16b7ff972c split up tdz into an optional transformer until it has a better implementation - fixes #527 2015-01-19 08:54:04 +11:00
Sebastian McKenzie
ca41612109 use process.stdin.write instead of console.log to avoid console.log sprintf - fixes #527 2015-01-19 08:53:42 +11:00
Sebastian McKenzie
8fc7af5480 properly reference method body - fixes #530 2015-01-19 08:35:01 +11:00
Aluísio Augusto Silva Gonçalves
7e6da1d368 Add tests for the externalRegenerator transformer 2015-01-18 17:33:57 -02:00
Aluísio Augusto Silva Gonçalves
d4cc8fefd1 Add transformer to import regeneratorRuntime from a module
Thanks to facebook/regenerator#167 Regenerator's runtime can be now
required as a module (though not in an easily self-containable way).
This transformer, together with `coreAliasing` and `externalRuntime`,
allows users to ditch a runtime dependency on `6to5`/`6to5-core` to
depend directly on `core-js` and `regenerator`.
2015-01-18 17:33:56 -02:00
Aluísio Augusto Silva Gonçalves
81bec3e5c4 Move the _blockHoist transformer after regenerator
Otherwise wrapped generator functions are hoisted to the top of the
scope even if we want something else to come before them.
2015-01-18 17:33:55 -02:00
Aluísio Augusto Silva Gonçalves
e985d8b25d Don't use interopRequire for dynamic imports
They don't need it at all and this also allows use of `externalRuntime`
without fear of the runtime ending up being loaded after it's used.
2015-01-18 17:31:55 -02:00
Aluísio Augusto Silva Gonçalves
84ee0efe32 Add test for externalRuntime with AMD modules 2015-01-18 17:31:54 -02:00
Aluísio Augusto Silva Gonçalves
e9a024e58a Add simple test for externalRuntime transformer
Just import a module namespace and see what happens.
2015-01-18 17:31:53 -02:00
Aluísio Augusto Silva Gonçalves
e8237910e8 Add a transformer to import the runtime from a file
The `externalRuntime` optional transformer can be used in conjunction
with the `runtime` option to import and use the runtime from a module
instead of polluting the global environment.
2015-01-18 17:31:52 -02:00
Sebastian McKenzie
1c6cb7ce40 Merge pull request #526 from tricknotes/remove-unused
Remove unused local variable
2015-01-18 22:30:24 +11:00
Ryunosuke SATO
24d6c3f488 Remove unused local variable
`hasOptional` is assigned but unused from anywhere.
2015-01-18 20:16:32 +09:00
Sebastian McKenzie
d877a04397 v2.13.1 2015-01-18 21:40:21 +11:00
Sebastian McKenzie
4844882f5e break let scoping transformer if there are no block scoped references 2015-01-18 21:37:37 +11:00
Sebastian McKenzie
a80945cfb4 ignore function declarations in TDZ detection 2015-01-18 21:33:22 +11:00
Sebastian McKenzie
6a884c58a7 add 2.13.1 changelog 2015-01-18 21:28:34 +11:00
Sebastian McKenzie
7c4701716c implement block scoping TDZ 2015-01-18 21:26:02 +11:00
Sebastian McKenzie
ecfd5fadc6 v2.13.0 2015-01-18 19:31:07 +11:00
Sebastian McKenzie
c6be5cccd7 update bin/6to5/file to new source-map api 2015-01-18 19:29:18 +11:00
Sebastian McKenzie
dd256dc3f8 add acorn-6to5 changes to 2.13.0 changelog 2015-01-18 19:26:15 +11:00
Sebastian McKenzie
622da331a6 add 2.13.0 changelog 2015-01-18 19:24:54 +11:00
Sebastian McKenzie
5a44793dcb upgrade acorn-6to5 2015-01-18 19:24:49 +11:00
Sebastian McKenzie
9c9a9b0325 make regenerator test future-proof 2015-01-18 18:51:11 +11:00
Sebastian McKenzie
2534f7f2a0 upgrade dependencies 2015-01-18 18:50:58 +11:00
Sebastian McKenzie
36a933a004 add strict mode to every file 2015-01-18 18:44:08 +11:00
Sebastian McKenzie
62c168b13c fix linting errors 2015-01-18 18:41:24 +11:00
Sebastian McKenzie
810c97d7ab actually make destructuring use the provided operator 2015-01-18 18:24:16 +11:00
Sebastian McKenzie
c2b20b18b3 make name method helper export a property method instead of a default 2015-01-18 18:24:05 +11:00
Sebastian McKenzie
309d19960f better traversal context variable names 2015-01-18 18:23:46 +11:00
Sebastian McKenzie
774cb66d9b add isBlockedScoped types helper 2015-01-18 18:23:37 +11:00
Sebastian McKenzie
d360bd5bb7 update misc tests 2015-01-18 18:23:27 +11:00
Sebastian McKenzie
74f5a73d31 update traceur 2015-01-18 18:23:14 +11:00
Sebastian McKenzie
26395a86fa add block scoped functions - fixes #514 2015-01-18 18:23:03 +11:00
Sebastian McKenzie
436c488ee3 revamp let scoping transformer - closes #510 2015-01-18 18:22:37 +11:00
Sebastian McKenzie
93d99077e5 Revert "add loose mode to spread and destructuring"
This reverts commit 95d9f59668.
2015-01-18 12:52:16 +11:00
Sebastian McKenzie
0bb52d6e3d Merge branch 'master' of github.com:6to5/6to5 2015-01-18 12:16:23 +11:00
Sebastian McKenzie
320c78b815 make let scoping collision detection much more reliable 2015-01-18 12:15:50 +11:00
Sebastian McKenzie
ddd59b94b0 upgrade acorn-6to5 2015-01-18 12:15:31 +11:00
Sebastian McKenzie
c210d64557 add loose all option 2015-01-18 12:13:08 +11:00
Sebastian McKenzie
a0f605bbab add way to automatically write expected tests 2015-01-18 12:12:58 +11:00
Sebastian McKenzie
f4b2768194 add todo note to duplicate expression 2015-01-18 12:12:32 +11:00
Sebastian McKenzie
95d9f59668 add loose mode to spread and destructuring 2015-01-18 12:12:12 +11:00
Sebastian McKenzie
c41d799b9b Merge pull request #522 from fabiomcosta/lint_fixes
Fixes lint warnings that are blocking test run
2015-01-18 10:21:12 +11:00
Fabio M. Costa
e7d4642d48 Fixes lint warnings that are blocking test run 2015-01-17 14:19:54 -08:00
Sebastian McKenzie
41949fd58b push uids to scope tracking - fixes #515 2015-01-18 02:36:37 +11:00
Sebastian McKenzie
d0dc972840 fix up formatting in traverse 2015-01-18 02:35:19 +11:00
Sebastian McKenzie
621e66e9ac add private declaration and comprehension expression support to scope tracking and id building 2015-01-18 02:35:08 +11:00
Sebastian McKenzie
529544ce0e use generateUidIdentifier instead of generateUid 2015-01-18 01:16:09 +11:00
Sebastian McKenzie
f298cd3f0f allow single idents in binary assignment operator transformer 2015-01-18 01:15:35 +11:00
Sebastian McKenzie
67029ac8e8 better helpers for assignment operators 2015-01-18 00:37:51 +11:00
Sebastian McKenzie
b54800234f clean up conditional assignment operator transformers 2015-01-17 22:56:49 +11:00
Sebastian McKenzie
ecd85f53b4 Merge pull request #516 from jridgewell/mallot
Playground Proposal: Mallet operator
2015-01-17 21:59:23 +11:00
Sebastian McKenzie
9098852897 abstract out classes super replace 2015-01-17 18:53:49 +11:00
Sebastian McKenzie
3eb4d5b466 fix up styling of #518 2015-01-17 18:53:40 +11:00
Sebastian McKenzie
ddb1c718f1 Merge pull request #518 from gaearon/perf-v8
RFC: V8-specific performance impovements
2015-01-17 18:33:35 +11:00
Sebastian McKenzie
8919873ea1 clean up react/jsx transformer 2015-01-17 18:26:14 +11:00
Sebastian McKenzie
eb9cd95d5a update for head tests 2015-01-17 17:54:04 +11:00
Sebastian McKenzie
4ec701fc44 ignore variable declarations inside loop head in newline generation - fixes #519 2015-01-17 17:44:16 +11:00
Dan Abramov
ff9511d435 Proof of concept of how traversal would look like with state parameter 2015-01-17 05:03:23 +03:00
Justin Ridgewell
ac5a6da1fa Use all falsey values 2015-01-16 19:25:28 -05:00
Justin Ridgewell
616640a128 Playground Proposal: Mallet operator
The mallet operator is similar to the current memoization operator,
except it can be used outside of just objects.

In Ruby, it’s almost the same as `a = a || b`. Note that only `nil` and
`false` are falsey in Ruby. I’ve defined it as `== null`, though that
could be changed to any JS falsey value.
2015-01-16 18:57:15 -05:00
Sebastian McKenzie
1f9ce96e43 fix rest parameter array size error in rest parameter comment 2015-01-17 10:27:01 +11:00
Sebastian McKenzie
dc6a862bec better clarification of rest parameter size construction comment 2015-01-17 10:23:53 +11:00
Dan Abramov
f9480b5280 Avoid closures when traversing 2015-01-17 00:13:39 +03:00
Dan Abramov
8dc4996547 Refactor traversal into smaller methods 2015-01-17 00:13:39 +03:00
Dan Abramov
4f01f67dd6 Avoid delete in favor of null assignment to prevent deoptimizations 2015-01-17 00:13:39 +03:00
Dan Abramov
938026abeb Use toFastProperties to speed up t.* method access 2015-01-17 00:13:38 +03:00
Sebastian McKenzie
76b8945207 v2.12.6 2015-01-16 22:52:12 +11:00
Sebastian McKenzie
e78859fae0 add 2.12.6 changelog 2015-01-16 22:49:31 +11:00
Sebastian McKenzie
d68f1e9910 add flow type generation skeleton 2015-01-16 22:47:55 +11:00
Sebastian McKenzie
20e97f2d9b add flow type visitor keys - none currently as we don't need to traverse over any of them - closes #513 2015-01-16 22:46:09 +11:00
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
bb19f24923 remove roadrunner from 6to5-node 2015-01-15 01:08:12 +11:00
Sebastian McKenzie
0cbcbc60de allow imports and exports everywhere in loose mode 2015-01-14 15:21:45 +11:00
Sebastian McKenzie
f33cd7184f add jsx to possible extensions 2015-01-14 15:09:15 +11:00
Sebastian McKenzie
59d6400eb9 remove ignoreRegex fallback 2015-01-14 15:06:12 +11:00
Sebastian McKenzie
5c575ebf8f remove fast transformer backwards compatibility 2015-01-14 14:58:15 +11:00
Sebastian McKenzie
274205bccd Merge branch 'master' into 3.0.0
Conflicts:
	CHANGELOG.md
	package.json
2015-01-14 14:56:55 +11:00
Sebastian McKenzie
e85c9b633a enable require hook cache by default - shove it into into a temp directory - don't cache require resolutions 2015-01-14 14:55:30 +11:00
Sebastian McKenzie
fbb150cfc1 remove allowImportExportEverywhere 2015-01-13 00:10:12 +11:00
659 changed files with 5721 additions and 5866 deletions

2
.gitignore vendored
View File

@@ -11,3 +11,5 @@ test/tmp
coverage
dist
.package.json
packages/6to5-runtime/*.js
packages/6to5-runtime/regenerator/*.js

2
.gitmodules vendored
View File

@@ -3,7 +3,7 @@
url = https://github.com/google/traceur-compiler
[submodule "vendor/regenerator"]
path = vendor/regenerator
url = https://github.com/facebook/regenerator
url = https://github.com/6to5/regenerator-6to5
[submodule "vendor/test262"]
path = vendor/test262
url = https://github.com/tc39/test262

60
.jscsrc Normal file
View File

@@ -0,0 +1,60 @@
{
"excludeFiles": ["lib/6to5/transformation/templates"],
"disallowSpacesInNamedFunctionExpression": {
"beforeOpeningRoundBrace": true
},
"requireSpacesInAnonymousFunctionExpression": {
"beforeOpeningRoundBrace": true
},
"requireSpacesInAnonymousFunctionExpression": {
"beforeOpeningRoundBrace": true
},
"disallowSpacesInFunctionDeclaration": {
"beforeOpeningRoundBrace": true
},
"disallowSpacesInsideArrayBrackets": true,
"disallowSpacesInsideParentheses": true,
"disallowQuotedKeysInObjects": true,
"disallowSpaceAfterObjectKeys": true,
"disallowSpaceAfterPrefixUnaryOperators": true,
"disallowSpaceBeforePostfixUnaryOperators": true,
"disallowSpaceBeforeBinaryOperators": [
","
],
"disallowMixedSpacesAndTabs": true,
"disallowTrailingWhitespace": true,
"disallowYodaConditions": true,
"disallowKeywords": [ "with" ],
"disallowMultipleLineBreaks": true,
"requireSpaceBeforeBlockStatements": true,
"requireParenthesesAroundIIFE": true,
"requireSpacesInConditionalExpression": true,
"requireBlocksOnNewline": 1,
"requireCommaBeforeLineBreak": true,
"requireSpaceBeforeBinaryOperators": true,
"requireSpaceAfterBinaryOperators": true,
"requireCamelCaseOrUpperCaseIdentifiers": true,
"requireLineFeedAtFileEnd": true,
"requireCapitalizedConstructors": true,
"requireDotNotation": true,
"requireSpacesInForStatement": true,
"requireCurlyBraces": [
"do"
],
"requireSpaceAfterKeywords": [
"if",
"else",
"for",
"while",
"do",
"switch",
"case",
"return",
"try",
"catch",
"typeof"
],
"validateLineBreaks": "LF",
"validateQuoteMarks": "\"",
"validateIndentation": 2
}

View File

@@ -1,3 +1 @@
node_modules
test
lib/6to5/transformation/templates

View File

@@ -10,3 +10,6 @@ dist
tests.json
CHANGELOG.md
.package.json
coverage
vendor
packages

View File

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

View File

@@ -11,6 +11,182 @@
_Note: Gaps between patch versions are faulty/broken releases._
## 3.0.0
* **Polish**
* Generated code autoindentation.
* Moved global uid registry to a scope registry resulting in nicer uids.
* `this` is now illegal in the top level scope when using the default `useStrict` transformer.
* New `asyncToGenerator` helper that's much more compact.
* Throw errors on unknown options.
* More reliable default parameter scope.
* Helpers are now compact and have no newlines.
* **Internal**
* Rewritten a lot of the internals to much simpler.
* Removed TDZ from default parameters as it was very wonky and unreliable.
* Upgrade `core-js` to `0.4.6`.
* Upgrade `acorn-6to5`.
* JSX support is now on-par with react-tools/esprima.
* Shorthand destructuring.
* **Bug Fix**
* Generators now work flawlessly with any parameter transformers.
* Optional async function transformers should not name their functions.
* Remove `unlink` event watching in `bin/6to5`.
* Fix regenerator variable declarations being incorrectly hoisted breaking scope.
* Transformers that attempted to simplify expressions that had no consequence now take into account whether it's one of the last statements/expressions in the script.
* **New Feature**
* New `selfContained` transformer.
* New `undeclaredVariableCheck` optional transformer.
* Added `--blacklist` and `--whitelist` options to `6to5-node`.
* **Breaking Change**
* Caching is now always enabled for the require hook. It also now no longer caches require resolutions.
* Bare `super();` only works inside of constructors.
* Removed the optional runtime in favor of the `selfContained` transformer.
* This shorthand has been removed from the playground.
* `6to5/polyfill` can now only be required **once**.
* **CLI**
* `--indent` option has been removed.
* `--include-regenerator` option has been removed.
* `--amd-modules-id` option has been removed, use `--module-ids` instead.
* **Options**
* `amdModuleIds` option has been removed, use `moduleIds` instead.
* `includeRegenerator` has been removed.
* `ignoreRegex` fallback has now been dropped from the require hook. `register(/foo/);`, `register({ ignoreRegex: /foo/ })` -> `register({ ignore: /foo/ })`.
* **Modules**
* Module interop now only collapses to `module.exports` when there's a **single** export that's default.
* Imports and exports are now illegal anywhere except the root level by default. Set `modules` to [loose mode](http://6to5.org/docs/usage/loose) to allow them everywhere.
* **Transformers**
* Optional fast transformer backwards compatibility support has been removed. Use [loose mode](https://6to5.org/docs/usage/loose).
* Removed the `coreAliasing` transformer in favor of `selfContained`.
* Renamed transformers:
* `specNoForInOfAssignment` -> `validation.noForInOfAssignment`
* `specSetters` -> `validation.setters`
* `specBlockScopedFunctions` -> `spec.blockScopedFunctions`
* `malletOperator` -> `playground.malletOperator`
* `methodBinding` -> `playground.methodBinding`
* `memoizationOperator` -> `playground.memoizationOperator`
* `objectGetterMemoization` -> `playground.objectGetterMemoization`
* `modules` -> `es6.modules`
* `propertyNameShorthand` -> `es6.properties.shorthand`
* `arrayComprehension` -> `es7.comprehensions`
* `generatorComprehension` -> `es7.comprehensions`
* `arrowFunctions` -> `es6.arrowFunctions`
* `classes` -> `es6.classes`
* `objectSpread` -> `es7.objectSpread`
* `exponentiationOperator` -> `es7.exponentiationOperator`
* `spread` -> `es6.spread`
* `templateLiterals` -> `es6.templateLiterals`
* `propertyMethodAssignment` -> `es6.properties.shorthand`
* `computedPropertyNames` -> `es6.properties.computed`
* `defaultParameters` -> `es6.parameters.default`
* `restParameters` -> `es6.parameters.rest`
* `destructuring` -> `es6.destructuring`
* `forOf` -> `es6.forOf`
* `unicodeRegex` -> `es6.unicodeRegex`
* `abstractReferences` -> `es7.abstractReferences`
* `constants` -> `es6.constants`
* `letScoping` -> `es6.blockScoping`
* `blockScopingTDZ` -> `es6.blockScopingTDZ`
* `generators` -> `regenerator`
* `protoToAssign` -> `spec.protoToAssign`
* `typeofSymbol` -> `spec.typeofSymbol`
* `coreAliasing` -> `selfContained`
* `undefinedToVoid` -> `spec.undefinedToVoid`
* `undeclaredVariableCheck` -> `validation.undeclaredVariableCheck`
* `specPropertyLiterals` -> `minification.propertyLiterals`
* `specMemberExpressionLiterals` -> `minification.memberExpressionLiterals`
## 2.13.7
* **Bug Fix**
* Don't realias variables that are already declared in optional `coreAliasing` transformer.
## 2.13.6
* **Bug Fix**
* Add `NewExpression` as a valid parent for parentheses insertion for `ConditionalExpression`.
## 2.13.5
* **Bug Fix**
* Allow rest parameters to be destructuring patterns.
* **Internal**
* Upgrade `kexec` to `1.1.0`.
## 2.13.4
* **Bug Fix**
* Fix ordering of destructuring and default params.
* Fix loop body scope.
* Fix `for...of` transformation not retaining it's scope.
* Add destructuring assignment support to scope tracking.
* **Polish**
* More reliable newlines for pretty printing variable declarations.
## 2.13.3
* **Internal**
* Add `coverage` and `vendor` to npmignore.
## 2.13.2
* **Bug Fix**
* Fix `super` inside of nested functions.
* **Internal**
* Move let scoping TDZ into a separate transformer until it's more solid.
* Use `process.stdin.write` instead of `console.log` in `bin` to avoid sprintfification.
## 2.13.1
* **New Feature**
* Temporal dead zone for block binding.
## 2.13.0
* **New Feature**
* Block scoped functions.
* Add `--loose all` option.
* Add playground mallet operator thanks to [@jridgewell](https://github.com/jridgewell).
* **Bug Fix**
* Rewrote large parts of the let scoping transformer. Now passes all known tests.
* **Internal**
* Even more optimisations thanks to the awesome [@gaearon](https://github.com/gaearon).
* Upgrade `acorn-6to5`.
* Fixes exponentation operator thanks to [@charliesome](https://github.com/charliesome).
* Fix flow optional parameters with types.
* Upgrade `chokidar` to `0.12.6`.
* Upgrade `commander` to `2.6.0`.
* Upgrade `core-js` to `0.4.5`.
* Upgrade `estraverse` to `1.9.1`.
* Upgrade `jshint` to `2.5.11`.
* Upgrade `regenerator` to `0.8.9`.
* Upgrade `regexpu` to `1.0.0`.
* Upgrade `source-map` to `0.1.43`.
* Upgrade `source-map-support` to `0.2.9`.
* Upgrade `browserify` to `8.1.1`.
* Upgrade `chai` to `1.10.0`.
* Upgrade `istanbul` to `0.3.5`.
* Upgrade `mocha` to `2.1.0`.
* Upgrade `uglify-js` to `2.4.16`.
## 2.12.6
* **Bug Fix**
* Add missing flow type traversal keys.
## 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**

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,17 +1,19 @@
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 --mangle sort
UGLIFY_CMD = node_modules/uglify-js/bin/uglifyjs
#UGLIFY_CMD = node_modules/uglify-js/bin/uglifyjs --mangle sort
JSHINT_CMD = node_modules/jshint/bin/jshint
MOCHA_CMD = node_modules/mocha/bin/_mocha
JSCS_CMD = node_modules/jscs/bin/jscs
export NODE_ENV = test
.PHONY: clean test test-cov test-clean lint test-travis test-simple test-all test-browser publish build bootstrap publish-core
.PHONY: clean test test-cov test-clean lint test-travis test-simple test-all test-browser publish build bootstrap publish-core publish-runtime
build:
mkdir -p dist
node bin/cache-templates
node tools/cache-templates
node $(BROWSERIFY_CMD) -e lib/6to5/polyfill.js >dist/polyfill.js
node $(UGLIFY_CMD) dist/polyfill.js >dist/polyfill.min.js
@@ -19,9 +21,6 @@ build:
node $(BROWSERIFY_CMD) lib/6to5/browser.js -s to5 >dist/6to5.js
node $(UGLIFY_CMD) dist/6to5.js >dist/6to5.min.js
node bin/6to5-runtime >dist/runtime.js
node $(UGLIFY_CMD) dist/runtime.js >dist/runtime.min.js
rm -rf templates.json
clean:
@@ -29,6 +28,7 @@ clean:
lint:
$(JSHINT_CMD) --reporter node_modules/jshint-stylish/stylish.js lib bin
$(JSCS_CMD) lib bin
test-clean:
rm -rf test/tmp
@@ -39,17 +39,17 @@ test: lint
test-simple:
# excludes test262
export SIMPLE_6TO5_TESTS=1
export SIMPLE_6TO5_TESTS=1; \
make test
test-all:
# includes traceur, esnext, regenerator
export ALL_6TO5_TESTS=1
export ALL_6TO5_TESTS=1; \
make test
test-cov:
export SIMPLE_6TO5_TESTS=1
rm -rf coverage
export SIMPLE_6TO5_TESTS=1; \
node $(ISTANBUL_CMD) $(MOCHA_CMD) --
test-travis: bootstrap
@@ -59,8 +59,8 @@ test-travis: bootstrap
test-browser:
mkdir -p dist
node bin/cache-templates
node bin/cache-tests
node tools/cache-templates
node tools/cache-tests
node $(BROWSERIFY_CMD) -e test/_browser.js >dist/6to5-test.js
rm -rf templates.json tests.json
@@ -77,28 +77,35 @@ publish:
make build
cp dist/6to5.min.js browser.js
cp dist/polyfill.min.js browser-polyfill.js
cp dist/runtime.min.js runtime.js
node bin/cache-templates
node tools/cache-templates
test -f templates.json
npm publish
git push --follow-tags
# generate
bin/generate-core-package-json >package2.json
make publish-core
make publish-runtime
rm -rf templates.json browser.js browser-polyfill.js
publish-runtime:
cd packages; \
node build-runtime.js; \
cd 6to5-runtime; \
npm publish
publish-core:
tools/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:
npm install
git submodule update --init

View File

@@ -1,13 +1,3 @@
# Notes
* 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,4 +0,0 @@
#!/usr/bin/env node
var runtime = require("../lib/6to5/runtime-generator");
console.log(runtime(process.argv[2]));

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);
};
@@ -54,7 +51,7 @@ module.exports = function (commander, filenames, opts) {
ignoreInitial: true
});
_.each(["add", "change", "unlink"], function (type) {
_.each(["add", "change"], function (type) {
watcher.on(type, function (filename) {
// chop off the dirname plus the path separator
var relative = filename.slice(dirname.length + 1);

View File

@@ -28,7 +28,7 @@ module.exports = function (commander, filenames) {
map.setSourceContent(filename, result.actual);
consumer.eachMapping(function (mapping) {
map._mappings.push({
map._mappings.add({
generatedLine: mapping.generatedLine + offset,
generatedColumn: mapping.generatedColumn,
originalLine: mapping.originalLine,
@@ -63,7 +63,7 @@ module.exports = function (commander, filenames) {
fs.writeFileSync(commander.outFile, result.code);
} else {
console.log(result.code);
process.stdout.write(result.code + "\n");
}
};
@@ -77,7 +77,7 @@ module.exports = function (commander, filenames) {
if (chunk !== null) code += chunk;
});
process.stdin.on("end", function() {
process.stdin.on("end", function () {
results.push(util.transform(commander.filename, code));
output();
});
@@ -117,7 +117,7 @@ module.exports = function (commander, filenames) {
persistent: true,
ignoreInitial: true
}).on("all", function (type, filename) {
if (type === "add" || type === "change" || type === "unlink" ) {
if (type === "add" || type === "change") {
console.log(type, filename);
walk();
}

View File

@@ -10,7 +10,6 @@ commander.option("-t, --source-maps-inline", "Append sourceMappingURL comment to
commander.option("-s, --source-maps", "Save source map alongside the compiled code");
commander.option("-f, --filename [filename]", "Filename to use when reading from stdin - this will be used in source-maps, errors etc [stdin]", "stdin");
commander.option("-w, --watch", "Recompile files on changes");
commander.option("-r, --runtime", "Replace 6to5 declarations with references to a runtime");
commander.option("-e, --experimental", "Enable experimental support for proposed ES7 features");
commander.option("-p, --playground", "Enable playground support");
@@ -18,29 +17,23 @@ commander.option("-m, --modules [modules]", "Module formatter type to use [commo
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("-L, --loose [list]", "List of transformers to enable loose mode ON", util.list);
commander.option("-o, --out-file [out]", "Compile all input files into a single file");
commander.option("-d, --out-dir [out]", "Compile an input directory of modules into an output directory");
commander.option("-c, --remove-comments", "Remove comments from the compiled code", false);
commander.option("-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(){
commander.on("--help", function () {
var outKeys = function (title, obj) {
console.log(" " + title + ":");
console.log();
var hasOptional = true;
_.each(_.keys(obj).sort(), function (key) {
if (key[0] === "_") return;
if (obj[key].optional) {
hasOptional = true;
key = "[" + key + "]";
}
@@ -104,25 +97,18 @@ if (errors.length) {
exports.opts = {
keepModuleIdExtensions: commander.keepModuleIdExtensions,
includeRegenerator: commander.includeRegenerator,
sourceMapName: commander.outFile,
experimental: commander.experimental,
reactCompat: commander.reactCompat,
playground: commander.playground,
moduleIds: commander.amdModuleIds || commander.moduleIds,
moduleIds: 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))
}
}
loose: commander.loose
};
var fn;

View File

@@ -1,40 +1,39 @@
#!/usr/bin/env node
var roadrunner = require("roadrunner");
var commander = require("commander");
var Module = require("module");
var path = require("path");
var repl = require("repl");
var to5 = require("../lib/6to5");
var util = require("../lib/6to5/util");
var vm = require("vm");
var _ = require("lodash");
var commander = require("commander");
var Module = require("module");
var path = require("path");
var repl = require("repl");
var to5 = require("../lib/6to5");
var util = require("../lib/6to5/util");
var vm = require("vm");
var _ = require("lodash");
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("-p, --print [code]", "Evaluate script and print result");
program.option("-i, --ignore [regex]", "Ignore all files that match this regex when using the require hook");
program.option("-x, --extensions [extensions]", "List of extensions to hook into [.es6,.js]");
program.option("-x, --extensions [extensions]", "List of extensions to hook into [.es6,.js,.es,.jsx]");
program.option("-r, --experimental", "Enable experimental support for proposed ES7 features");
program.option("-g, --playground", "Enable playground support");
program.option("-c, --cache", "Cache compiled files and require paths");
program.option("-w, --whitelist [whitelist]", "Whitelist of transformers to ONLY use", util.list);
program.option("-b, --blacklist [blacklist]", "Blacklist of transformers to NOT use", util.list);
var pkg = require("../package.json");
program.version(pkg.version);
program.usage("[options] [ -e script | script.js ] [arguments]");
program.parse(process.argv);
if (program.cache) roadrunner.load();
//
to5.register({
experimental: program.experimental,
extensions: program.extensions,
playground: program.playground,
ignore: program.ignore,
cache: program.cache && roadrunner.get("6to5")
blacklist: program.blacklist,
whitelist: program.whitelist,
ignore: program.ignore
});
//
@@ -42,15 +41,19 @@ to5.register({
var _eval = function (code, filename) {
code = to5.transform(code, {
filename: filename,
blacklist: ["useStrict"],
blacklist: ["useStrict"].concat(program.blacklist || []),
whitelist: program.whitelist,
experimental: program.experimental,
playground: program.playground
}).code;
return vm.runInThisContext(code, filename);
};
if (program.eval) {
var result = _eval(program.eval, "eval");
if (program.eval || program.print) {
var code = program.eval;
if (!code || code === true) code = program.print;
var result = _eval(code, "eval");
if (program.print) console.log(result);
} else {
if (program.args.length) {
@@ -79,8 +82,6 @@ if (program.eval) {
}
}
if (program.cache) roadrunner.save();
function replStart() {
repl.start({
prompt: "> ",

View File

@@ -1,3 +1,5 @@
"use strict";
var transform = module.exports = require("./transformation/transform");
transform.version = require("../../package").version;

View File

@@ -1,21 +1,30 @@
"use strict";
module.exports = File;
var SHEBANG_REGEX = /^\#\!.*/;
var transform = require("./transformation/transform");
var generate = require("./generation/generator");
var clone = require("./helpers/clone");
var Scope = require("./traverse/scope");
var util = require("./util");
var t = require("./types");
var _ = require("lodash");
function File(opts) {
this.dynamicImports = [];
this.dynamicImportIds = {};
this.dynamicImported = [];
this.dynamicImports = [];
this.dynamicData = {};
this.data = {};
this.lastStatements = [];
this.opts = File.normaliseOptions(opts);
this.transformers = this.getTransformers();
this.uids = {};
this.ast = {};
this.buildTransformers();
}
File.helpers = [
@@ -40,23 +49,46 @@ File.helpers = [
"get"
];
File.excludeHelpersFromRuntime = [
"async-to-generator",
"typeof",
"tagged-template-literal-loose"
File.validOptions = [
"filename",
"filenameRelative",
"blacklist",
"whitelist",
"loose",
"optional",
"modules",
"sourceMap",
"sourceMapName",
"sourceFileName",
"sourceRoot",
"moduleRoot",
"moduleIds",
"comments",
"reactCompat",
"keepModuleIdExtensions",
"code",
"ast",
"format",
"playground",
"experimental"
];
File.normaliseOptions = function (opts) {
opts = _.cloneDeep(opts || {});
opts = clone(opts);
for (var key in opts) {
if (File.validOptions.indexOf(key) < 0) {
throw new ReferenceError("Unknown option: " + key);
}
}
_.defaults(opts, {
keepModuleIdExtensions: false,
includeRegenerator: false,
experimental: false,
reactCompat: false,
playground: false,
whitespace: true,
moduleIds: opts.amdModuleIds || false,
moduleIds: false,
blacklist: [],
whitelist: [],
sourceMap: false,
@@ -64,7 +96,6 @@ File.normaliseOptions = function (opts) {
comments: true,
filename: "unknown",
modules: "common",
runtime: false,
loose: [],
code: true,
ast: true
@@ -78,16 +109,9 @@ File.normaliseOptions = function (opts) {
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);
}
});
if (_.contains(opts.loose, "all")) {
opts.loose = Object.keys(transform.transformers);
}
_.defaults(opts, {
moduleRoot: opts.sourceRoot
@@ -106,18 +130,14 @@ File.normaliseOptions = function (opts) {
sourceMapName: opts.filenameRelative
});
if (opts.runtime === true) {
opts.runtime = "to5Runtime";
}
if (opts.playground) {
opts.experimental = true;
}
transform._ensureTransformerNames("blacklist", opts.blacklist);
transform._ensureTransformerNames("whitelist", opts.whitelist);
transform._ensureTransformerNames("optional", opts.optional);
transform._ensureTransformerNames("loose", opts.loose);
opts.blacklist = transform._ensureTransformerNames("blacklist", opts.blacklist);
opts.whitelist = transform._ensureTransformerNames("whitelist", opts.whitelist);
opts.optional = transform._ensureTransformerNames("optional", opts.optional);
opts.loose = transform._ensureTransformerNames("loose", opts.loose);
return opts;
};
@@ -126,17 +146,21 @@ File.prototype.isLoose = function (key) {
return _.contains(this.opts.loose, key);
};
File.prototype.getTransformers = function () {
File.prototype.buildTransformers = function () {
var file = this;
var transformers = [];
var secondPassTransformers = [];
_.each(transform.transformers, function (transformer) {
if (transformer.canRun(file)) {
transformers.push(transformer);
var transformers = {};
var secondaryStack = [];
var stack = [];
_.each(transform.transformers, function (transformer, key) {
var pass = transformers[key] = transformer.buildPass(file);
if (pass.canRun(file)) {
stack.push(pass);
if (transformer.secondPass) {
secondPassTransformers.push(transformer);
secondaryStack.push(pass);
}
if (transformer.manipulateOptions) {
@@ -145,7 +169,8 @@ File.prototype.getTransformers = function () {
}
});
return transformers.concat(secondPassTransformers);
this.transformerStack = stack.concat(secondaryStack);
this.transformers = transformers;
};
File.prototype.toArray = function (node, i) {
@@ -191,6 +216,26 @@ File.prototype.parseShebang = function (code) {
return code;
};
File.prototype.set = function (key, val) {
return this.data[key] = val;
};
File.prototype.setDynamic = function (key, fn) {
this.dynamicData[key] = fn;
};
File.prototype.get = function (key) {
var data = this.data[key];
if (data) {
return data;
} else {
var dynamic = this.dynamicData[key];
if (dynamic) {
return this.set(key, dynamic());
}
}
};
File.prototype.addImport = function (source, name) {
name = name || source;
var id = this.dynamicImportIds[name];
@@ -201,12 +246,18 @@ File.prototype.addImport = function (source, name) {
var specifiers = [t.importSpecifier(t.identifier("default"), id)];
var declar = t.importDeclaration(specifiers, t.literal(source));
declar._blockHoist = 3;
this.dynamicImports.push(declar);
this.dynamicImported.push(declar);
this.moduleFormatter.importSpecifier(specifiers[0], declar, this.dynamicImports);
}
return id;
};
File.prototype.isConsequenceExpressionStatement = function (node) {
return t.isExpressionStatement(node) && this.lastStatements.indexOf(node) >= 0;
};
File.prototype.addHelper = function (name) {
if (!_.contains(File.helpers, name)) {
throw new ReferenceError("unknown declaration " + name);
@@ -217,22 +268,21 @@ File.prototype.addHelper = function (name) {
var declar = program._declarations && program._declarations[name];
if (declar) return declar.id;
var ref;
var runtimeNamespace = this.opts.runtime;
if (runtimeNamespace && !_.contains(File.excludeHelpersFromRuntime, name)) {
var runtime = this.get("runtimeIdentifier");
if (runtime) {
name = t.identifier(t.toIdentifier(name));
return t.memberExpression(t.identifier(runtimeNamespace), name);
return t.memberExpression(runtime, name);
} else {
ref = util.template(name);
var ref = util.template(name);
ref._compact = true;
var uid = this.generateUidIdentifier(name);
this.scope.push({
key: name,
id: uid,
init: ref
});
return uid;
}
var uid = this.generateUidIdentifier(name);
this.scope.push({
key: name,
id: uid,
init: ref
});
return uid;
};
File.prototype.errorWithNode = function (node, msg, Error) {
@@ -255,7 +305,11 @@ File.prototype.parse = function (code) {
code = this.addCode(code);
return util.parse(this.opts, code, function (tree) {
var opts = this.opts;
opts.allowImportExportEverywhere = this.isLoose("modules");
return util.parse(opts, code, function (tree) {
self.transform(tree);
return self.generate();
});
@@ -265,19 +319,20 @@ File.prototype.transform = function (ast) {
var self = this;
this.ast = ast;
this.scope = new Scope(ast.program);
this.lastStatements = t.getLastStatements(ast.program);
this.scope = new Scope(ast.program, null, this);
this.moduleFormatter = this.getModuleFormatter(this.opts.modules);
var astRun = function (key) {
_.each(self.transformers, function (transformer) {
transformer.astRun(self, key);
_.each(self.transformerStack, function (pass) {
pass.astRun(key);
});
};
astRun("enter");
_.each(this.transformers, function (transformer) {
transformer.transform(self);
_.each(this.transformerStack, function (pass) {
pass.transform();
});
astRun("exit");
@@ -289,6 +344,7 @@ File.prototype.generate = function () {
var result = {
code: "",
opts: opts,
map: null,
ast: null
};
@@ -318,22 +374,23 @@ File.prototype.generateUid = function (name, scope) {
scope = scope || this.scope;
var uid;
var i = 0;
do {
uid = this._generateUid(name);
uid = this._generateUid(name, i);
i++;
} while (scope.has(uid));
return uid;
};
File.prototype.generateUidIdentifier = function (name, scope) {
return t.identifier(this.generateUid(name, scope));
scope = scope || this.scope;
var id = t.identifier(this.generateUid(name, scope));
scope.add(id);
return id;
};
File.prototype._generateUid = function (name) {
var uids = this.uids;
var i = uids[name] || 1;
File.prototype._generateUid = function (name, i) {
var id = name;
if (i > 1) id += i;
uids[name] = i + 1;
return "_" + id;
};

View File

@@ -1,3 +1,5 @@
"use strict";
module.exports = Buffer;
var util = require("../util");
@@ -66,33 +68,62 @@ Buffer.prototype.removeLast = function (cha) {
};
Buffer.prototype.newline = function (i, removeLast) {
if (this.format.compact) return;
if (_.isBoolean(i)) {
removeLast = i;
i = null;
if (this.format.compact) {
this.space();
return;
}
removeLast = removeLast || false;
if (_.isNumber(i)) {
if (this.endsWith("{\n")) i--;
if (this.endsWith(util.repeat(i, "\n"))) return;
for (var j = 0; j < i; j++) {
this.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

View File

@@ -1,3 +1,5 @@
"use strict";
module.exports = function (ast, opts, code) {
var gen = new CodeGenerator(ast, opts, code);
return gen.generate();
@@ -5,21 +7,22 @@ module.exports = function (ast, opts, code) {
module.exports.CodeGenerator = CodeGenerator;
var Whitespace = require("./whitespace");
var SourceMap = require("./source-map");
var Position = require("./position");
var Buffer = require("./buffer");
var util = require("../util");
var n = require("./node");
var t = require("../types");
var _ = require("lodash");
var detectIndent = require("detect-indent");
var Whitespace = require("./whitespace");
var SourceMap = require("./source-map");
var Position = require("./position");
var Buffer = require("./buffer");
var util = require("../util");
var n = require("./node");
var t = require("../types");
var _ = require("lodash");
function CodeGenerator(ast, opts, code) {
opts = opts || {};
this.comments = ast.comments || [];
this.tokens = ast.tokens || [];
this.format = CodeGenerator.normaliseOptions(opts);
this.format = CodeGenerator.normaliseOptions(code, opts);
this.ast = ast;
this.whitespace = new Whitespace(this.tokens, this.comments);
@@ -34,14 +37,18 @@ _.each(Buffer.prototype, function (fn, key) {
};
});
CodeGenerator.normaliseOptions = function (opts) {
CodeGenerator.normaliseOptions = function (code, opts) {
var indent = detectIndent(code);
var style = indent.indent;
if (!style || style === " ") style = " ";
return _.merge({
parentheses: true,
comments: opts.comments == null || opts.comments,
compact: false,
indent: {
adjustMultilineComment: true,
style: " ",
style: style,
base: 0
}
}, opts.format || {});
@@ -114,6 +121,15 @@ CodeGenerator.prototype.buildPrint = function (parent) {
CodeGenerator.prototype.print = function (node, parent, opts) {
if (!node) return "";
if (parent && parent._compact) {
node._compact = true;
}
var oldCompact = this.format.compact;
if (node._compact) {
this.format.compact = true;
}
var self = this;
opts = opts || {};
@@ -178,6 +194,8 @@ CodeGenerator.prototype.print = function (node, parent, opts) {
} else {
throw new ReferenceError("unknown node of type " + JSON.stringify(node.type) + " with constructor " + JSON.stringify(node && node.constructor.name));
}
this.format.compact = oldCompact;
};
CodeGenerator.prototype.printJoin = function (print, nodes, opts) {

View File

@@ -1,3 +1,5 @@
"use strict";
exports.File = function (node, print) {
print(node.program);
};

View File

@@ -1,3 +1,5 @@
"use strict";
exports.ClassExpression =
exports.ClassDeclaration = function (node, print) {
this.push("class");

View File

@@ -1,3 +1,5 @@
"use strict";
exports.ComprehensionBlock = function (node, print) {
this.keyword("for");
this.push("(");

View File

@@ -1,3 +1,5 @@
"use strict";
var util = require("../../util");
var t = require("../../types");
var _ = require("lodash");
@@ -110,7 +112,9 @@ exports.LogicalExpression =
exports.AssignmentPattern =
exports.AssignmentExpression = function (node, print) {
print(node.left);
this.push(" " + node.operator + " ");
this.space();
this.push(node.operator);
this.space();
print(node.right);
};

View File

@@ -1,3 +1,35 @@
exports.ClassProperty = function () {
throw new Error("not implemented");
"use strict";
exports.AnyTypeAnnotation =
exports.ArrayTypeAnnotation =
exports.BooleanTypeAnnotation =
exports.ClassProperty =
exports.DeclareClass =
exports.DeclareFunction =
exports.DeclareModule =
exports.DeclareVariable =
exports.FunctionTypeAnnotation =
exports.FunctionTypeParam =
exports.GenericTypeAnnotation =
exports.InterfaceExtends =
exports.InterfaceDeclaration =
exports.IntersectionTypeAnnotation =
exports.NullableTypeAnnotation =
exports.NumberTypeAnnotation =
exports.StringLiteralTypeAnnotation =
exports.StringTypeAnnotation =
exports.TupleTypeAnnotation =
exports.TypeofTypeAnnotation =
exports.TypeAlias =
exports.TypeAnnotation =
exports.TypeParameterDeclaration =
exports.TypeParameterInstantiation =
exports.ObjectTypeAnnotation =
exports.ObjectTypeCallProperty =
exports.ObjectTypeIndexer =
exports.ObjectTypeProperty =
exports.QualifiedTypeIdentifier =
exports.UnionTypeAnnotation =
exports.VoidTypeAnnotation = function () {
// todo: implement these once we have a `--keep-types` option
};

View File

@@ -1,7 +1,9 @@
"use strict";
var t = require("../../types");
var _ = require("lodash");
exports.XJSAttribute = function (node, print) {
exports.JSXAttribute = function (node, print) {
print(node.name);
if (node.value) {
this.push("=");
@@ -9,35 +11,35 @@ exports.XJSAttribute = function (node, print) {
}
};
exports.XJSIdentifier = function (node) {
exports.JSXIdentifier = function (node) {
this.push(node.name);
};
exports.XJSNamespacedName = function (node, print) {
exports.JSXNamespacedName = function (node, print) {
print(node.namespace);
this.push(":");
print(node.name);
};
exports.XJSMemberExpression = function (node, print) {
exports.JSXMemberExpression = function (node, print) {
print(node.object);
this.push(".");
print(node.property);
};
exports.XJSSpreadAttribute = function (node, print) {
exports.JSXSpreadAttribute = function (node, print) {
this.push("{...");
print(node.argument);
this.push("}");
};
exports.XJSExpressionContainer = function (node, print) {
exports.JSXExpressionContainer = function (node, print) {
this.push("{");
print(node.expression);
this.push("}");
};
exports.XJSElement = function (node, print) {
exports.JSXElement = function (node, print) {
var self = this;
var open = node.openingElement;
@@ -57,22 +59,22 @@ exports.XJSElement = function (node, print) {
print(node.closingElement);
};
exports.XJSOpeningElement = function (node, print) {
exports.JSXOpeningElement = function (node, print) {
this.push("<");
print(node.name);
if (node.attributes.length > 0) {
this.space();
this.push(" ");
print.join(node.attributes, { separator: " " });
}
this.push(node.selfClosing ? " />" : ">");
};
exports.XJSClosingElement = function (node, print) {
exports.JSXClosingElement = function (node, print) {
this.push("</");
print(node.name);
this.push(">");
};
exports.XJSEmptyExpression = function () {
exports.JSXEmptyExpression = function () {
};

View File

@@ -1,30 +1,14 @@
"use strict";
var t = require("../../types");
exports._params = function (node, print) {
var self = this;
this.push("(");
print.join(node.params, {
separator: ", ",
iterator: function (param, i) {
var def = node.defaults && node.defaults[i];
if (def) {
self.push(" = ");
print(def);
}
}
separator: ", "
});
if (node.rest) {
if (node.params.length) {
this.push(", ");
}
this.push("...");
print(node.rest);
}
this.push(")");
};
@@ -52,7 +36,7 @@ exports._method = function (node, print) {
}
this._params(value, print);
this.space();
this.push(" ");
print(value.body);
};
@@ -61,8 +45,11 @@ exports.FunctionExpression = function (node, print) {
if (node.async) this.push("async ");
this.push("function");
if (node.generator) this.push("*");
this.space();
if (node.id) print(node.id);
this.push(" ");
if (node.id) {
this.space();
print(node.id);
}
this._params(node, print);
this.space();
print(node.body);
@@ -71,7 +58,7 @@ exports.FunctionExpression = function (node, print) {
exports.ArrowFunctionExpression = function (node, print) {
if (node.async) this.push("async ");
if (node.params.length === 1 && !node.defaults.length && !node.rest && t.isIdentifier(node.params[0])) {
if (node.params.length === 1 && t.isIdentifier(node.params[0])) {
print(node.params[0]);
} else {
this._params(node, print);

View File

@@ -1,9 +1,11 @@
"use strict";
var t = require("../../types");
var _ = require("lodash");
exports.ImportSpecifier = function (node, print) {
if (node.id && node.id.name === "default") {
print(node.name);
if (t.isSpecifierDefault(node)) {
print(t.getSpecifierName(node));
} else {
return exports.ExportSpecifier.apply(this, arguments);
}
@@ -69,7 +71,7 @@ exports.ImportDeclaration = function (node, print) {
self.push(", ");
}
var isDefault = spec.id && spec.id.name === "default";
var isDefault = t.isSpecifierDefault(spec);
if (!isDefault && spec.type !== "ImportBatchSpecifier" && !foundImportSpecifier) {
foundImportSpecifier = true;

View File

@@ -1,3 +1,5 @@
"use strict";
var _ = require("lodash");
_.each(["BindMemberExpression", "BindFunctionExpression"], function (type) {

View File

@@ -1,3 +1,5 @@
"use strict";
var util = require("../../util");
var t = require("../../types");
@@ -13,12 +15,13 @@ exports.IfStatement = function (node, print) {
this.keyword("if");
this.push("(");
print(node.test);
this.push(") ");
this.push(")");
this.space();
print.indentOnComments(node.consequent);
if (node.alternate) {
if (this.isLast("}")) this.space();
if (this.isLast("}")) this.push(" ");
this.keyword("else");
print.indentOnComments(node.alternate);
}
@@ -32,13 +35,13 @@ exports.ForStatement = function (node, print) {
this.push(";");
if (node.test) {
this.space();
this.push(" ");
print(node.test);
}
this.push(";");
if (node.update) {
this.space();
this.push(" ");
print(node.update);
}
@@ -85,7 +88,7 @@ var buildLabelStatement = function (prefix, key) {
var label = node[key || "label"];
if (label) {
this.space();
this.push(" ");
print(label);
}
@@ -142,7 +145,9 @@ exports.SwitchStatement = function (node, print) {
this.keyword("switch");
this.push("(");
print(node.discriminant);
this.push(") {");
this.push(")");
this.space();
this.push("{");
print.sequence(node.cases, { indent: true });
this.push("}");
};
@@ -167,18 +172,19 @@ exports.DebuggerStatement = function () {
exports.VariableDeclaration = function (node, print, parent) {
this.push(node.kind + " ");
var inits = 0;
var noInits = 0;
for (var i in node.declarations) {
if (node.declarations[i].init) {
inits++;
} else {
noInits++;
var hasInits = false;
// don't add whitespace to loop heads
if (!t.isFor(parent)) {
for (var i = 0; i < node.declarations.length; i++) {
if (node.declarations[i].init) {
// has an init so let's split it up over multiple lines
hasInits = true;
}
}
}
var sep = ",";
if (inits > noInits) { // more inits than noinits
if (hasInits) {
sep += "\n" + util.repeat(node.kind.length + 1);
} else {
sep += " ";
@@ -200,7 +206,9 @@ exports.PrivateDeclaration = function (node, print) {
exports.VariableDeclarator = function (node, print) {
if (node.init) {
print(node.id);
this.push(" = ");
this.space();
this.push("=");
this.space();
print(node.init);
} else {
print(node.id);

View File

@@ -1,3 +1,5 @@
"use strict";
var _ = require("lodash");
exports.TaggedTemplateExpression = function (node, print) {

View File

@@ -1,9 +1,12 @@
"use strict";
var _ = require("lodash");
exports.Identifier = function (node) {
this.push(node.name);
};
exports.RestElement =
exports.SpreadElement =
exports.SpreadProperty = function (node, print) {
this.push("...");

View File

@@ -1,3 +1,5 @@
"use strict";
module.exports = Node;
var whitespace = require("./whitespace");
@@ -13,7 +15,7 @@ var find = function (obj, node, parent) {
for (var i = 0; i < types.length; i++) {
var type = types[i];
if (t["is" + type](node)) {
if (t.is(type, node)) {
var fn = obj[type];
result = fn(node, parent);
if (result != null) break;
@@ -28,13 +30,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)) {
@@ -51,18 +51,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) {
@@ -77,10 +74,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
@@ -100,17 +94,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 skipCount = 2;
var args = new Array(arguments.length - skipCount);
var args = new Array(arguments.length + 2);
args[0] = this.node;
args[1] = this.parent;
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i + 2];
args[i + 2] = arguments[i];
}
return n[key].apply(n, args);
return Node[key].apply(null, args);
};
});

View File

@@ -1,3 +1,5 @@
"use strict";
var t = require("../../types");
var _ = require("lodash");
@@ -149,8 +151,10 @@ exports.ConditionalExpression = function (node, parent) {
return true;
}
if (t.isCallExpression(parent) && parent.callee === node) {
return true;
if (t.isCallExpression(parent) || t.isNewExpression(parent)) {
if (parent.callee === node) {
return true;
}
}
if (t.isConditionalExpression(parent) && parent.test === node) {

View File

@@ -1,3 +1,5 @@
"use strict";
var _ = require("lodash");
var t = require("../../types");

View File

@@ -1,3 +1,5 @@
"use strict";
module.exports = Position;
function Position() {

View File

@@ -1,3 +1,5 @@
"use strict";
module.exports = SourceMap;
var sourceMap = require("source-map");

View File

@@ -1,10 +1,40 @@
"use strict";
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) {
@@ -13,13 +43,17 @@ Whitespace.prototype.getNewlinesBefore = function (node) {
var tokens = this.tokens;
var token;
for (var i = 0; i < tokens.length; i++) {
for (var j = 0; j < tokens.length; j++) {
// optimize for forward traversal by shifting for loop index
var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length);
token = tokens[i];
// this is the token this node starts with
if (node.start === token.start) {
startToken = tokens[i - 1];
endToken = token;
this._lastFoundIndex = i;
break;
}
}
@@ -33,13 +67,17 @@ Whitespace.prototype.getNewlinesAfter = function (node) {
var tokens = this.tokens;
var token;
for (var i = 0; i < tokens.length; i++) {
for (var j = 0; j < tokens.length; j++) {
// optimize for forward traversal by shifting for loop index
var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length);
token = tokens[i];
// this is the token this node ends with
if (node.end === token.end) {
startToken = token;
endToken = tokens[i + 1];
this._lastFoundIndex = i;
break;
}
}
@@ -60,12 +98,11 @@ Whitespace.prototype.getNewlinesAfter = function (node) {
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++;
}
}

12
lib/6to5/helpers/clone.js Normal file
View File

@@ -0,0 +1,12 @@
"use strict";
module.exports = function cloneDeep(obj) {
var obj2 = {};
if (!obj) return obj2;
for (var key in obj) {
obj2[key] = obj[key];
}
return obj2;
};

View File

@@ -0,0 +1,79 @@
// syntax highlighting based on https://github.com/dominictarr/ansi-highlight by the fantastic Dominic Tarr
var supportsColor = require("supports-color");
var tokenize = require("js-tokenizer");
var chalk = require("chalk");
var util = require("../util");
var defs = {
string1: "red",
string2: "red",
punct: ["white", "bold"],
curly: "green",
parens: ["blue", "bold"],
square: ["yellow"],
name: "white",
keyword: ["cyan"],
number: "magenta",
regexp: "magenta",
comment1: "grey",
comment2: "grey"
};
var highlight = function (text) {
var colorize = function (str, col) {
if (!col) return str;
if (Array.isArray(col)) {
col.forEach(function (col) {
str = chalk[col](str);
});
} else {
str = chalk[col](str);
}
return str;
};
return tokenize(text, true).map(function (str) {
var type = tokenize.type(str);
return colorize(str, defs[type]);
}).join("");
};
module.exports = function (lines, lineNumber, colNumber) {
colNumber = Math.max(colNumber, 0);
if (supportsColor) {
lines = highlight(lines);
}
lines = lines.split("\n");
var start = Math.max(lineNumber - 3, 0);
var end = Math.min(lines.length, lineNumber + 3);
var width = (end + "").length;
if (!lineNumber && !colNumber) {
start = 0;
end = lines.length;
}
return "\n" + lines.slice(start, end).map(function (line, i) {
var curr = i + start + 1;
var gutter = curr === lineNumber ? "> " : " ";
var sep = curr + util.repeat(width + 1);
gutter += sep + "| ";
var str = gutter + line;
if (colNumber && curr === lineNumber) {
str += "\n";
str += util.repeat(gutter.length - 2);
str += "|" + util.repeat(colNumber) + "^";
}
return str;
}).join("\n");
};

View File

@@ -0,0 +1,5 @@
"use strict";
module.exports = function () {
return Object.create(null);
};

View File

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

View File

@@ -1,3 +1,5 @@
"use strict";
var transform = require("./transformation/transform");
var util = require("./util");
var fs = require("fs");
@@ -7,8 +9,6 @@ exports.version = require("../../package").version;
exports.types = require("./types");
exports.runtime = require("./runtime-generator");
exports.register = function (opts) {
var register = require("./register");
if (opts != null) register(opts);

View File

@@ -1,22 +1,31 @@
"use strict";
var t = require("./types");
var _ = require("lodash");
require("./types/node");
// estraverse
var estraverse = require("estraverse");
_.extend(estraverse.VisitorKeys, t.VISITOR_KEYS);
// regenerator/recast/ast-types
// regenerator-6to5/ast-types
var types = require("ast-types");
var def = types.Type.def;
var or = types.Type.or;
def("File")
.bases("Node")
.build("program")
.field("program", def("Program"));
def("AssignmentPattern")
.bases("Pattern")
.build("left", "right")
.field("left", def("Pattern"))
.field("right", def("Expression"));
.bases("Pattern")
.build("left", "right")
.field("left", def("Pattern"))
.field("right", def("Expression"));
// Acorn - Same as ImportNamespaceSpecifier but `id` is `name`
def("ImportBatchSpecifier")
@@ -24,6 +33,11 @@ def("ImportBatchSpecifier")
.build("name")
.field("name", def("Identifier"));
def("RestElement")
.bases("Node")
.build("argument")
.field("argument", def("Pattern"));
// Abstract references
def("VirtualPropertyExpression")
.bases("Expression")

View File

@@ -1,2 +1,9 @@
"use strict";
if (global._6to5Polyfill) {
throw new Error("only one instance of 6to5/polyfill is allowed");
}
global._6to5Polyfill = true;
require("core-js/shim");
require("regenerator/runtime");
require("regenerator-6to5/runtime");

View File

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

View File

@@ -0,0 +1,36 @@
"use strict";
var path = require("path");
var os = require("os");
var fs = require("fs");
var FILENAME = path.join(os.tmpdir(), "6to5.json");
var data = {};
exports.save = function () {
fs.writeFileSync(FILENAME, JSON.stringify(data, null, " "));
};
exports.load = function () {
if (!fs.existsSync(FILENAME)) return;
try {
data = JSON.parse(fs.readFileSync(FILENAME));
} catch (err) {
return;
}
process.on("exit", exports.save);
var sigint = function () {
process.removeListener("SIGINT", sigint);
exports.save();
process.kill(process.pid, "SIGINT");
};
process.on("SIGINT", sigint);
};
exports.get = function () {
return data;
};

View File

@@ -1,7 +1,9 @@
"use strict";
require("./polyfill");
var sourceMapSupport = require("source-map-support");
var roadrunner = require("roadrunner");
var registerCache = require("./register-cache");
var util = require("./util");
var to5 = require("./index");
var fs = require("fs");
@@ -23,46 +25,8 @@ 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"); });
registerCache.load();
var cache = registerCache.get();
//
@@ -70,7 +34,6 @@ var transformOpts = {};
var ignoreRegex = /node_modules/;
var onlyRegex;
var whitelist = [];
var cache;
var exts = {};
var maps = {};
var old = require.extensions[".js"];
@@ -95,7 +58,6 @@ var loader = function (m, filename) {
result = result || to5.transformFileSync(filename, _.extend({
whitelist: whitelist,
blacklist: blacklist,
sourceMap: true,
ast: false
}, transformOpts));
@@ -128,21 +90,18 @@ hookExtensions(util.canCompile.EXTENSIONS);
module.exports = function (opts) {
// normalise options
opts = opts || {};
if (_.isRegExp(opts)) opts = { ignore: opts };
if (opts.ignoreRegex != null) opts.ignore = opts.ignoreRegex;
if (opts.only != null) onlyRegex = util.regexify(opts.only);
if (opts.ignore != null) ignoreRegex = util.regexify(opts.ignore);
if (opts.extensions) hookExtensions(util.arrayify(opts.extensions));
if (opts.cache) cache = opts.cache;
if (opts.cache === false) cache = null;
if (opts.cache === true) {
roadrunner.load();
roadrunner.setup();
cache = roadrunner.get("6to5");
}
delete opts.extensions;
delete opts.ignore;
delete opts.cache;
delete opts.only;
_.extend(transformOpts, opts);
};

View File

@@ -1,33 +0,0 @@
var generator = require("./generation/generator");
var util = require("./util");
var File = require("./file");
var t = require("./types");
var _ = require("lodash");
module.exports = function (namespace) {
namespace = t.identifier(t.toIdentifier(namespace || "to5Runtime"));
var body = [];
var container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body));
var tree = t.program([t.expressionStatement(t.callExpression(container, [util.template("self-global")]))]);
body.push(t.variableDeclaration("var", [
t.variableDeclarator(
namespace,
t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace), t.objectExpression([]))
)
]));
_.each(File.helpers, function (name) {
if (_.contains(File.excludeHelpersFromRuntime, name)) {
return;
}
var key = t.identifier(t.toIdentifier(name));
body.push(t.expressionStatement(
t.assignmentExpression("=", t.memberExpression(namespace, key), util.template(name))
));
});
return generator(tree).code;
};

View File

@@ -0,0 +1,46 @@
"use strict";
var explode = require("./explode-assignable-expression");
var t = require("../../types");
module.exports = function (exports, opts) {
var isAssignment = function (node) {
return node.operator === opts.operator + "=";
};
var buildAssignment = function (left, right) {
return t.assignmentExpression("=", left, right);
};
exports.ExpressionStatement = function (node, parent, scope, context, file) {
// hit the `AssignmentExpression` one below
if (file.isConsequenceExpressionStatement(node)) return;
var expr = node.expression;
if (!isAssignment(expr)) return;
var nodes = [];
var exploded = explode(expr.left, nodes, file, scope, true);
nodes.push(t.expressionStatement(
buildAssignment(exploded.ref, opts.build(exploded.uid, expr.right))
));
return nodes;
};
exports.AssignmentExpression = function (node, parent, scope, context, file) {
if (!isAssignment(node)) return;
var nodes = [];
var exploded = explode(node.left, nodes, file, scope);
nodes.push(buildAssignment(exploded.ref, opts.build(exploded.uid, node.right)));
return t.toSequenceExpression(nodes, scope);
};
exports.BinaryExpression = function (node) {
if (node.operator !== opts.operator) return;
return opts.build(node.left, node.right);
};
};

View File

@@ -0,0 +1,25 @@
"use strict";
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,47 @@
"use strict";
var explode = require("./explode-assignable-expression");
var t = require("../../types");
module.exports = function (exports, opts) {
var buildAssignment = function (left, right) {
return t.assignmentExpression("=", left, right);
};
exports.ExpressionStatement = function (node, parent, scope, context, file) {
// hit the `AssignmentExpression` one below
if (file.isConsequenceExpressionStatement(node)) return;
var expr = node.expression;
if (!opts.is(expr, file)) return;
var nodes = [];
var exploded = explode(expr.left, nodes, file, scope);
nodes.push(t.ifStatement(
opts.build(exploded.uid, file),
t.expressionStatement(buildAssignment(exploded.ref, expr.right))
));
return nodes;
};
exports.AssignmentExpression = function (node, parent, scope, context, file) {
if (!opts.is(node, file)) return;
var nodes = [];
var exploded = explode(node.left, nodes, file, scope);
nodes.push(t.logicalExpression(
"&&",
opts.build(exploded.uid, file),
buildAssignment(exploded.ref, node.right)
));
// todo: duplicate expression node
nodes.push(exploded.ref);
return t.toSequenceExpression(nodes, scope);
};
};

View File

@@ -0,0 +1,73 @@
"use strict";
var t = require("../../types");
var getObjRef = function (node, nodes, file, scope) {
var ref;
if (t.isIdentifier(node)) {
if (scope.has(node.name, true)) {
// this variable is declared in scope so we can be 100% sure
// that evaluating it multiple times wont trigger a getter
// or something else
return node;
} else {
// could possibly trigger a getter so we need to only evaluate
// it once
ref = node;
}
} else if (t.isMemberExpression(node)) {
ref = node.object;
if (t.isIdentifier(ref) && scope.has(ref.name)) {
// the object reference that we need to save is locally declared
// so as per the previous comment we can be 100% sure evaluating
// it multiple times will be safe
return ref;
}
} else {
throw new Error("We can't explode this node type " + node.type);
}
var temp = scope.generateUidBasedOnNode(ref);
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(temp, ref)
]));
return temp;
};
var getPropRef = function (node, nodes, file, scope) {
var prop = node.property;
var key = t.toComputedKey(node, prop);
if (t.isLiteral(key)) return key;
var temp = scope.generateUidBasedOnNode(prop);
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(temp, prop)
]));
return temp;
};
module.exports = function (node, nodes, file, scope, allowedSingleIdent) {
var obj;
if (t.isIdentifier(node) && allowedSingleIdent) {
obj = node;
} else {
obj = getObjRef(node, nodes, file, scope);
}
var ref, uid;
if (t.isIdentifier(node)) {
ref = node;
uid = obj;
} else {
var prop = getPropRef(node, nodes, file, scope);
var computed = node.computed || t.isLiteral(prop);
uid = ref = t.memberExpression(obj, prop, computed);
}
return {
uid: uid,
ref: ref
};
};

View File

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

View File

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

View File

@@ -0,0 +1,251 @@
"use strict";
module.exports = ReplaceSupers;
var traverse = require("../../traverse");
var t = require("../../types");
/**
* Description
*
* @param {Object} opts
*/
function ReplaceSupers(opts) {
this.topLevelThisReference = null;
this.methodNode = opts.methodNode;
this.className = opts.className;
this.superName = opts.superName;
this.isLoose = opts.isLoose;
this.scope = opts.scope;
this.file = opts.file;
}
/**
* Gets a node representing the super class value of the named property.
*
* @example
*
* _get(Object.getPrototypeOf(CLASS.prototype), "METHOD", this)
*
* @param {Node} property
* @param {boolean} isStatic
* @param {boolean} isComputed
*
* @returns {Node}
*/
ReplaceSupers.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}
*/
ReplaceSupers.prototype.looseSuperProperty = function (methodNode, id, parent) {
var methodName = methodNode.key;
var superName = this.superName || t.identifier("Function");
if (parent.property === id) {
return;
} else if (t.isCallExpression(parent, { callee: id })) {
// super(); -> ClassName.prototype.MethodName.call(this);
parent.arguments.unshift(t.thisExpression());
if (methodName.name === "constructor") {
// constructor() { super(); }
return t.memberExpression(superName, t.identifier("call"));
} else {
id = superName;
// foo() { super(); }
if (!methodNode.static) {
id = t.memberExpression(id, t.identifier("prototype"));
}
id = t.memberExpression(id, methodName, methodNode.computed);
return t.memberExpression(id, t.identifier("call"));
}
} else if (t.isMemberExpression(parent) && !methodNode.static) {
// super.test -> ClassName.prototype.test
return t.memberExpression(superName, t.identifier("prototype"));
} else {
return superName;
}
};
/**
* Description
*/
ReplaceSupers.prototype.replace = function () {
this.traverseLevel(this.methodNode.value, true);
};
var visitor = {
enter: function (node, parent, scope, context, state) {
var topLevel = state.topLevel;
var self = state.self;
if (t.isFunction(node) && !t.isArrowFunctionExpression(node)) {
// we need to call traverseLevel again so we're context aware
self.traverseLevel(node, false);
return context.skip();
}
if (t.isProperty(node, { method: true }) || t.isMethodDefinition(node)) {
// break on object methods
return context.skip();
}
var getThisReference = topLevel ?
// top level so `this` is the instance
t.thisExpression :
// not in the top level so we need to create a reference
self.getThisReference;
var callback = self.specHandle;
if (self.isLoose) callback = self.looseHandle;
return callback.call(self, getThisReference, node, parent);
}
};
/**
* Description
*
* @param {Object} node
* @param {Boolean} topLevel
*/
ReplaceSupers.prototype.traverseLevel = function (node, topLevel) {
var state = { self: this, topLevel: topLevel };
traverse(node, visitor, this.scope, state);
};
/**
* Description
*/
ReplaceSupers.prototype.getThisReference = function () {
if (this.topLevelThisReference) {
return this.topLevelThisReference;
} else {
var ref = this.topLevelThisReference = this.file.generateUidIdentifier("this");
this.methodNode.value.body.body.unshift(t.variableDeclaration("var", [
t.variableDeclarator(this.topLevelThisReference, t.thisExpression())
]));
return ref;
}
};
/**
* Description
*
* @param {Function} getThisReference
* @param {Object} node
* @param {Object} parent
*/
ReplaceSupers.prototype.looseHandle = function (getThisReference, node, parent) {
if (t.isIdentifier(node, { name: "super" })) {
return this.looseSuperProperty(this.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());
}
};
/**
* Description
*
* @param {Function} getThisReference
* @param {Object} node
* @param {Object} parent
*/
ReplaceSupers.prototype.specHandle = function (getThisReference, node, parent) {
var methodNode = this.methodNode;
var property;
var computed;
var args;
if (t.isIdentifier(node, { name: "super" })) {
if (!(t.isMemberExpression(parent) && !parent.computed && parent.property === node)) {
throw this.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;
// bare `super` call is illegal inside non-constructors
// - https://esdiscuss.org/topic/super-call-in-methods
// - https://twitter.com/wycats/status/544553184396836864
if (methodNode.key.name !== "constructor") {
var methodName = methodNode.key.name || "METHOD_NAME";
throw this.file.errorWithNode(node, "Direct super call is illegal in non-constructor, use super." + methodName + "() instead");
}
} else {
if (!t.isMemberExpression(callee)) return;
if (callee.object.name !== "super") return;
// 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 = this.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;
}
};

View File

@@ -1,13 +1,15 @@
"use strict";
var t = require("../../types");
exports._has = function (node) {
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) {
exports.wrap = function (node, callback) {
var useStrictNode;
if (exports._has(node)) {
if (exports.has(node)) {
useStrictNode = node.body.shift();
}
@@ -17,11 +19,3 @@ exports._wrap = function (node, callback) {
node.body.unshift(useStrictNode);
}
};
exports.ast = {
exit: function (ast) {
if (!exports._has(ast.program)) {
ast.program.body.unshift(t.expressionStatement(t.literal("use strict")));
}
}
};

View File

@@ -1,81 +1,135 @@
"use strict";
module.exports = DefaultFormatter;
var traverse = require("../../traverse");
var object = require("../../helpers/object");
var util = require("../../util");
var t = require("../../types");
var _ = require("lodash");
function DefaultFormatter(file) {
this.file = file;
this.ids = object();
this.localExports = this.getLocalExports();
this.localImports = this.getLocalImports();
this.hasNonDefaultExports = false;
this.hasLocalExports = false;
this.hasLocalImports = false;
this.localImportOccurences = object();
this.localExports = object();
this.localImports = object();
this.getLocalExports();
this.getLocalImports();
this.remapAssignments();
//this.checkCollisions();
}
DefaultFormatter.prototype.getLocalExports = function () {
var localExports = {};
DefaultFormatter.prototype.doDefaultExportInterop = function (node) {
return node.default && !this.noInteropRequire && !this.hasNonDefaultExports;
};
traverse(this.file.ast, {
enter: function (node) {
var declar = node && node.declaration;
if (t.isExportDeclaration(node) && declar && t.isStatement(declar)) {
_.extend(localExports, t.getIds(declar, true));
DefaultFormatter.prototype.bumpImportOccurences = function (node) {
var source = node.source.value;
var occurs = this.localImportOccurences;
occurs[source] = occurs[source] || 0;
occurs[source] += node.specifiers.length;
};
var exportsVisitor = {
enter: function (node, parent, scope, context, formatter) {
var declar = node && node.declaration;
if (t.isExportDeclaration(node)) {
formatter.hasLocalImports = true;
if (declar && t.isStatement(declar)) {
_.extend(formatter.localExports, t.getIds(declar, true));
}
if (!node.default) {
formatter.hasNonDefaultExports = true;
}
if (node.source) {
formatter.bumpImportOccurences(node);
}
}
});
}
};
return localExports;
DefaultFormatter.prototype.getLocalExports = function () {
traverse(this.file.ast, exportsVisitor, this.file.scope, this);
};
var importsVisitor = {
enter: function (node, parent, scope, context, formatter) {
if (t.isImportDeclaration(node)) {
formatter.hasLocalImports = true;
_.extend(formatter.localImports, t.getIds(node, true));
formatter.bumpImportOccurences(node);
}
}
};
DefaultFormatter.prototype.getLocalImports = function () {
var localImports = {};
traverse(this.file.ast, {
enter: function (node) {
if (t.isImportDeclaration(node)) {
_.extend(localImports, t.getIds(node, true));
}
}
});
return localImports;
traverse(this.file.ast, importsVisitor, this.file.scope, this);
};
DefaultFormatter.prototype.checkCollisions = function () {
// todo: all check export collissions
var remapVisitor = {
enter: function (node, parent, scope, context, formatter) {
if (t.isUpdateExpression(node) && formatter.isLocalReference(node.argument, scope)) {
context.skip();
var localImports = this.localImports;
var file = this.file;
// expand to long file assignment expression
var assign = t.assignmentExpression(node.operator[0] + "=", node.argument, t.literal(1));
var isLocalReference = function (node) {
return t.isIdentifier(node) && _.has(localImports, node.name) && localImports[node.name] !== node;
};
// remap this assignment expression
var remapped = formatter.remapExportAssignment(assign);
var check = function (node) {
if (isLocalReference(node)) {
throw file.errorWithNode(node, "Illegal assignment of module import");
}
};
traverse(file.ast, {
enter: function (node) {
if (t.isAssignmentExpression(node)) {
var left = node.left;
if (t.isMemberExpression(left)) {
while (left.object) left = left.object;
}
check(left);
} else if (t.isDeclaration(node)) {
_.each(t.getIds(node, true), check);
// we don't need to change the result
if (t.isExpressionStatement(parent) || node.prefix) {
return remapped;
}
var nodes = [];
nodes.push(remapped);
var operator;
if (node.operator === "--") {
operator = "+";
} else { // "++"
operator = "-";
}
nodes.push(t.binaryExpression(operator, node.argument, t.literal(1)));
return t.sequenceExpression(nodes);
}
});
if (t.isAssignmentExpression(node) && formatter.isLocalReference(node.left, scope)) {
context.skip();
return formatter.remapExportAssignment(node);
}
}
};
DefaultFormatter.prototype.remapAssignments = function () {
if (this.hasLocalImports) {
traverse(this.file.ast, remapVisitor, this.file.scope, this);
}
};
DefaultFormatter.prototype.isLocalReference = function (node) {
var localImports = this.localImports;
return t.isIdentifier(node) && localImports[node.name] && localImports[node.name] !== node;
};
DefaultFormatter.prototype.checkLocalReference = function (node) {
var file = this.file;
if (this.isLocalReference(node)) {
throw file.errorWithNode(node, "Illegal assignment of module import");
}
};
DefaultFormatter.prototype.remapExportAssignment = function (node) {
@@ -90,51 +144,10 @@ DefaultFormatter.prototype.remapExportAssignment = function (node) {
);
};
DefaultFormatter.prototype.remapAssignments = function () {
DefaultFormatter.prototype.isLocalReference = function (node, scope) {
var localExports = this.localExports;
var self = this;
var isLocalReference = function (node, scope) {
var name = node.name;
return t.isIdentifier(node) && localExports[name] && localExports[name] === scope.get(name, true);
};
traverse(this.file.ast, {
enter: function (node, parent, scope) {
if (t.isUpdateExpression(node) && isLocalReference(node.argument, scope)) {
this.skip();
// expand to long file assignment expression
var assign = t.assignmentExpression(node.operator[0] + "=", node.argument, t.literal(1));
// remap this assignment expression
var remapped = self.remapExportAssignment(assign);
// we don't need to change the result
if (t.isExpressionStatement(parent) || node.prefix) {
return remapped;
}
var nodes = [];
nodes.push(remapped);
var operator;
if (node.operator === "--") {
operator = "+";
} else { // "++"
operator = "-";
}
nodes.push(t.binaryExpression(operator, node.argument, t.literal(1)));
return t.sequenceExpression(nodes);
}
if (t.isAssignmentExpression(node) && isLocalReference(node.left, scope)) {
this.skip();
return self.remapExportAssignment(node);
}
}
});
var name = node.name;
return t.isIdentifier(node) && localExports[name] && localExports[name] === scope.get(name, true);
};
DefaultFormatter.prototype.getModuleName = function () {
@@ -188,25 +201,37 @@ DefaultFormatter.prototype._hoistExport = function (declar, assign, priority) {
return assign;
};
DefaultFormatter.prototype._exportSpecifier = function (getRef, specifier, node, nodes) {
DefaultFormatter.prototype.getExternalReference = function (node, nodes) {
var ids = this.ids;
var id = node.source.value;
if (ids[id]) {
return ids[id];
} else {
return this.ids[id] = this._getExternalReference(node, nodes);
}
};
DefaultFormatter.prototype.exportSpecifier = function (specifier, node, nodes) {
var inherits = false;
if (node.specifiers.length === 1) inherits = node;
if (node.source) {
var ref = this.getExternalReference(node, nodes);
if (t.isExportBatchSpecifier(specifier)) {
// export * from "foo";
nodes.push(this._exportsWildcard(getRef(), node));
nodes.push(this.buildExportsWildcard(ref, node));
} else {
var ref;
if (t.isSpecifierDefault(specifier) && !this.noInteropRequire) {
// importing a default so we need to normalise it
ref = t.callExpression(this.file.addHelper("interop-require"), [getRef()]);
ref = t.callExpression(this.file.addHelper("interop-require"), [ref]);
} else {
ref = t.memberExpression(getRef(), specifier.id);
ref = t.memberExpression(ref, t.getSpecifierId(specifier));
}
// export { foo } from "test";
nodes.push(this._exportsAssign(
nodes.push(this.buildExportsAssignment(
t.getSpecifierName(specifier),
ref,
node
@@ -214,18 +239,18 @@ DefaultFormatter.prototype._exportSpecifier = function (getRef, specifier, node,
}
} else {
// export { foo };
nodes.push(this._exportsAssign(t.getSpecifierName(specifier), specifier.id, node));
nodes.push(this.buildExportsAssignment(t.getSpecifierName(specifier), specifier.id, node));
}
};
DefaultFormatter.prototype._exportsWildcard = function (objectIdentifier) {
DefaultFormatter.prototype.buildExportsWildcard = function (objectIdentifier) {
return t.expressionStatement(t.callExpression(this.file.addHelper("defaults"), [
t.identifier("exports"),
t.callExpression(this.file.addHelper("interop-require-wildcard"), [objectIdentifier])
]));
};
DefaultFormatter.prototype._exportsAssign = function (id, init) {
DefaultFormatter.prototype.buildExportsAssignment = function (id, init) {
return util.template("exports-assign", {
VALUE: init,
KEY: id
@@ -244,13 +269,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;
decl.init = this.buildExportsAssignment(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 {
@@ -261,7 +286,7 @@ DefaultFormatter.prototype.exportDeclaration = function (node, nodes) {
nodes.push(declar);
}
assign = this._exportsAssign(id, ref, node);
assign = this.buildExportsAssignment(id, ref, node);
nodes.push(assign);

View File

@@ -1,8 +1,10 @@
"use strict";
var util = require("../../util");
module.exports = function (Parent) {
var Constructor = function () {
this.noInteropExport = true;
this.noInteropRequire = true;
Parent.apply(this, arguments);
};

View File

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

View File

@@ -1,3 +1,5 @@
"use strict";
module.exports = AMDFormatter;
var DefaultFormatter = require("./_default");
@@ -8,7 +10,6 @@ var _ = require("lodash");
function AMDFormatter() {
CommonFormatter.apply(this, arguments);
this.ids = {};
}
util.inherits(AMDFormatter, DefaultFormatter);
@@ -66,33 +67,30 @@ AMDFormatter.prototype.getModuleName = function () {
}
};
AMDFormatter.prototype._push = function (node) {
var id = node.source.value;
var ids = this.ids;
if (ids[id]) {
return ids[id];
} else {
return this.ids[id] = this.file.generateUidIdentifier(id);
}
AMDFormatter.prototype._getExternalReference = function (node) {
return this.file.generateUidIdentifier(node.source.value);
};
AMDFormatter.prototype.importDeclaration = function (node) {
this._push(node);
this.getExternalReference(node);
};
AMDFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
var key = t.getSpecifierName(specifier);
var ref = this._push(node);
var ref = this.getExternalReference(node);
if (t.isImportBatchSpecifier(specifier)) {
if (_.contains(this.file.dynamicImported, node)) {
// Prevent unnecessary renaming of dynamic imports.
this.ids[node.source.value] = key;
return;
} else if (t.isImportBatchSpecifier(specifier)) {
// import * as bar from "foo";
} else if (t.isSpecifierDefault(specifier) && !this.noInteropRequire) {
// import foo from "foo";
ref = t.callExpression(this.file.addHelper("interop-require"), [ref]);
} else {
// import {foo} from "foo";
ref = t.memberExpression(ref, specifier.id, false);
ref = t.memberExpression(ref, t.getSpecifierId(specifier), false);
}
nodes.push(t.variableDeclaration("var", [
@@ -101,16 +99,9 @@ AMDFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
};
AMDFormatter.prototype.exportDeclaration = function (node) {
if (node.default && !this.noInteropExport) {
if (this.doDefaultExportInterop(node)) {
this.passModuleArg = true;
}
CommonFormatter.prototype.exportDeclaration.apply(this, arguments);
};
AMDFormatter.prototype.exportSpecifier = function (specifier, node, nodes) {
var self = this;
return this._exportSpecifier(function () {
return self._push(node);
}, specifier, node, nodes);
};

View File

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

View File

@@ -1,20 +1,18 @@
"use strict";
module.exports = CommonJSFormatter;
var DefaultFormatter = require("./_default");
var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
var _ = require("lodash");
function CommonJSFormatter(file) {
DefaultFormatter.apply(this, arguments);
var hasNonDefaultExports = false;
traverse(file.ast, {
enter: function (node) {
if (t.isExportDeclaration(node) && !node.default) hasNonDefaultExports = true;
}
});
this.hasNonDefaultExports = hasNonDefaultExports;
if (this.hasNonDefaultExports) {
file.ast.program.body.push(util.template("exports-module-declaration", true));
}
}
util.inherits(CommonJSFormatter, DefaultFormatter);
@@ -22,15 +20,14 @@ util.inherits(CommonJSFormatter, DefaultFormatter);
CommonJSFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
var variableName = t.getSpecifierName(specifier);
var ref = this.getExternalReference(node, nodes);
// import foo from "foo";
if (t.isSpecifierDefault(specifier)) {
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(variableName,
t.callExpression(this.file.addHelper("interop-require"), [util.template("require", {
MODULE_NAME: node.source
})])
)
]));
if (!_.contains(this.file.dynamicImported, node)) {
ref = t.callExpression(this.file.addHelper("interop-require"), [ref]);
}
nodes.push(t.variableDeclaration("var", [t.variableDeclarator(variableName, ref)]));
} else {
if (specifier.type === "ImportBatchSpecifier") {
// import * as bar from "foo";
@@ -38,17 +35,18 @@ CommonJSFormatter.prototype.importSpecifier = function (specifier, node, nodes)
t.variableDeclarator(
variableName,
t.callExpression(this.file.addHelper("interop-require-wildcard"), [
t.callExpression(t.identifier("require"), [node.source])
ref
])
)
]));
} else {
// import foo from "foo";
nodes.push(util.template("require-assign-key", {
VARIABLE_NAME: variableName,
MODULE_NAME: node.source,
KEY: specifier.id
}));
// import { foo } from "foo";
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(
variableName,
t.memberExpression(ref, t.getSpecifierId(specifier))
)
]));
}
}
};
@@ -61,45 +59,35 @@ CommonJSFormatter.prototype.importDeclaration = function (node, nodes) {
};
CommonJSFormatter.prototype.exportDeclaration = function (node, nodes) {
if (node.default && !this.noInteropRequire && !this.noInteropExport) {
if (this.doDefaultExportInterop(node)) {
var declar = node.declaration;
var assign;
var assign = util.template("exports-default-assign", {
VALUE: this._pushStatement(declar, nodes)
}, true);
// module.exports = VALUE;
var templateName = "exports-default-module";
// exports = module.exports = VALUE;
if (this.hasNonDefaultExports) templateName = "exports-default-module-override";
if (t.isFunctionDeclaration(declar) || !this.hasNonDefaultExports) {
assign = util.template(templateName, {
VALUE: this._pushStatement(declar, nodes)
}, true);
// hoist to the top if this default is a function
nodes.push(this._hoistExport(declar, assign, 3));
return;
} else {
// this export isn't a function so we can't hoist it to the top so we need to set it
// at the very end of the file with something like:
//
// module.exports = _extends(exports["default"], exports)
//
assign = util.template("common-export-default-assign", {
EXTENDS_HELPER: this.file.addHelper("extends")
}, true);
assign._blockHoist = 0;
nodes.push(assign);
if (t.isFunctionDeclaration(declar)) {
// we can hoist this assignment to the top of the file
assign._blockHoist = 3;
}
nodes.push(assign);
return;
}
DefaultFormatter.prototype.exportDeclaration.apply(this, arguments);
};
CommonJSFormatter.prototype.exportSpecifier = function (specifier, node, nodes) {
this._exportSpecifier(function () {
return t.callExpression(t.identifier("require"), [node.source]);
}, specifier, node, nodes);
CommonJSFormatter.prototype._getExternalReference = function (node, nodes) {
var source = node.source.value;
var call = t.callExpression(t.identifier("require"), [node.source]);
if (this.localImportOccurences[source] > 1) {
var uid = this.file.generateUidIdentifier(source);
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(uid, call)
]));
return uid;
} else {
return call;
}
};

View File

@@ -1,3 +1,5 @@
"use strict";
module.exports = IgnoreFormatter;
var t = require("../../types");

View File

@@ -0,0 +1,10 @@
module.exports = {
commonStrict: require("./common-strict"),
amdStrict: require("./amd-strict"),
umdStrict: require("./umd-strict"),
common: require("./common"),
system: require("./system"),
ignore: require("./ignore"),
amd: require("./amd"),
umd: require("./umd")
};

View File

@@ -1,17 +1,20 @@
"use strict";
module.exports = SystemFormatter;
var AMDFormatter = require("./amd");
var useStrict = require("../transformers/use-strict");
var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
var _ = require("lodash");
var DefaultFormatter = require("./_default");
var AMDFormatter = require("./amd");
var useStrict = require("../helpers/use-strict");
var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
var _ = require("lodash");
function SystemFormatter(file) {
this.exportIdentifier = file.generateUidIdentifier("export");
this.exportIdentifier = file.generateUidIdentifier("export");
this.noInteropRequire = true;
AMDFormatter.apply(this, arguments);
DefaultFormatter.apply(this, arguments);
}
util.inherits(SystemFormatter, AMDFormatter);
@@ -21,7 +24,7 @@ SystemFormatter.prototype._addImportSource = function (node, exportNode) {
return node;
};
SystemFormatter.prototype._exportsWildcard = function (objectIdentifier, node) {
SystemFormatter.prototype.buildExportsWildcard = function (objectIdentifier, node) {
var leftIdentifier = this.file.generateUidIdentifier("key");
var valIdentifier = t.memberExpression(objectIdentifier, leftIdentifier, true);
@@ -38,7 +41,7 @@ SystemFormatter.prototype._exportsWildcard = function (objectIdentifier, node) {
return this._addImportSource(t.forInStatement(left, right, block), node);
};
SystemFormatter.prototype._exportsAssign = function (id, init, node) {
SystemFormatter.prototype.buildExportsAssignment = function (id, init, node) {
var call = this.buildExportCall(t.literal(id.name), init, true);
return this._addImportSource(call, node);
};
@@ -61,31 +64,95 @@ SystemFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
this._addImportSource(_.last(nodes), node);
};
var runnerSettersVisitor = {
enter: function (node, parent, scope, context, state) {
if (node._importSource === state.source) {
if (t.isVariableDeclaration(node)) {
_.each(node.declarations, function (declar) {
state.hoistDeclarators.push(t.variableDeclarator(declar.id));
state.nodes.push(t.expressionStatement(
t.assignmentExpression("=", declar.id, declar.init)
));
});
} else {
state.nodes.push(node);
}
context.remove();
}
}
};
SystemFormatter.prototype.buildRunnerSetters = function (block, hoistDeclarators) {
var scope = this.file.scope;
return t.arrayExpression(_.map(this.ids, function (uid, source) {
var nodes = [];
var state = {
source: source,
nodes: [],
hoistDeclarators: hoistDeclarators
};
traverse(block, {
enter: function (node) {
if (node._importSource === source) {
if (t.isVariableDeclaration(node)) {
_.each(node.declarations, function (declar) {
hoistDeclarators.push(t.variableDeclarator(declar.id));
nodes.push(t.expressionStatement(
t.assignmentExpression("=", declar.id, declar.init)
));
});
} else {
nodes.push(node);
}
traverse(block, runnerSettersVisitor, scope, state);
this.remove();
return t.functionExpression(null, [uid], t.blockStatement(state.nodes));
}));
};
var hoistVariablesVisitor = {
enter: function (node, parent, scope, context, hoistDeclarators) {
if (t.isFunction(node)) {
// nothing inside is accessible
return context.skip();
}
if (t.isVariableDeclaration(node)) {
if (node.kind !== "var" && !t.isProgram(parent)) { // let, const
// can't be accessed
return;
}
// ignore block hoisted nodes as these can be left in
if (node._blockHoist) return;
var nodes = [];
for (var i = 0; i < node.declarations.length; i++) {
var declar = node.declarations[i];
hoistDeclarators.push(t.variableDeclarator(declar.id));
if (declar.init) {
// no initializer so we can just hoist it as-is
var assign = t.expressionStatement(t.assignmentExpression("=", declar.id, declar.init));
nodes.push(assign);
}
}
});
return t.functionExpression(null, [uid], t.blockStatement(nodes));
}));
// for (var i in test)
// for (var i = 0;;)
if (t.isFor(parent)) {
if (parent.left === node) {
return node.declarations[0].id;
}
if (parent.init === node) {
return t.toSequenceExpression(nodes, scope);
}
}
return nodes;
}
}
};
var hoistFunctionsVisitor = {
enter: function (node, parent, scope, context, handlerBody) {
if (t.isFunction(node)) context.skip();
if (t.isFunctionDeclaration(node) || node._blockHoist) {
handlerBody.push(node);
context.remove();
}
}
};
SystemFormatter.prototype.transform = function (ast) {
@@ -111,46 +178,8 @@ SystemFormatter.prototype.transform = function (ast) {
var returnStatement = handlerBody.pop();
// hoist up all variable declarations
traverse(block, {
enter: function (node, parent, scope) {
if (t.isFunction(node)) {
// nothing inside is accessible
return this.skip();
}
traverse(block, hoistVariablesVisitor, this.file.scope, hoistDeclarators);
if (t.isVariableDeclaration(node)) {
if (node.kind !== "var" && !t.isProgram(parent)) { // let, const
// can't be accessed
return;
}
var nodes = [];
_.each(node.declarations, function (declar) {
hoistDeclarators.push(t.variableDeclarator(declar.id));
if (declar.init) {
// no initializer so we can just hoist it as-is
var assign = t.expressionStatement(t.assignmentExpression("=", declar.id, declar.init));
nodes.push(assign);
}
});
// for (var i in test)
// for (var i = 0;;)
if (t.isFor(parent)) {
if (parent.left === node) {
return node.declarations[0].id;
}
if (parent.init === node) {
return t.toSequenceExpression(nodes, scope);
}
}
return nodes;
}
}
});
if (hoistDeclarators.length) {
var hoistDeclar = t.variableDeclaration("var", hoistDeclarators);
hoistDeclar._blockHoist = true;
@@ -158,20 +187,11 @@ SystemFormatter.prototype.transform = function (ast) {
}
// hoist up function declarations for circular references
traverse(block, {
enter: function (node) {
if (t.isFunction(node)) this.skip();
if (t.isFunctionDeclaration(node) || node._blockHoist) {
handlerBody.push(node);
this.remove();
}
}
});
traverse(block, hoistFunctionsVisitor, this.file.scope, handlerBody);
handlerBody.push(returnStatement);
if (useStrict._has(block)) {
if (useStrict.has(block)) {
handlerBody.unshift(block.body.shift());
}

View File

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

View File

@@ -1,3 +1,5 @@
"use strict";
module.exports = UMDFormatter;
var AMDFormatter = require("./amd");

View File

@@ -1,3 +0,0 @@
ARRAY.forEach(function (KEY) {
});

View File

@@ -3,35 +3,26 @@
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(getNext) {
var next;
var callNext = step.bind(gen.next);
var callThrow = step.bind(gen.throw);
function step(arg) {
try {
next = getNext();
} catch(e) {
reject(e);
var info = this(arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (next.done) {
resolve(next.value);
return;
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(callNext, callThrow);
}
Promise.resolve(next.value).then(function (v) {
step(function () {
return gen.next(v);
});
}, function (e) {
step(function () {
return gen["throw"](e);
});
});
}
step(function () {
return gen.next();
});
callNext();
});
}
};
})

View File

@@ -1 +0,0 @@
module.exports = EXTENDS_HELPER(exports["default"], exports);

View File

@@ -1 +0,0 @@
exports = module.exports = VALUE;

View File

@@ -0,0 +1 @@
exports.__esModule = true;

View File

@@ -2,7 +2,9 @@
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
target[key] = source[key];
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;

View File

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

View File

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

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

@@ -3,4 +3,3 @@
raw: { value: Object.freeze(raw) }
}));
});

View File

@@ -1,6 +1,9 @@
"use strict";
module.exports = transform;
var Transformer = require("./transformer");
var object = require("../helpers/object");
var File = require("../file");
var util = require("../util");
var _ = require("lodash");
@@ -19,84 +22,52 @@ transform.fromAst = function (ast, code, opts) {
return file.generate();
};
transform._ensureTransformerNames = function (type, keys) {
for (var i in keys) {
var key = keys[i];
if (!_.has(transform.transformers, key)) {
throw new ReferenceError("unknown transformer " + key + " specified in " + type);
transform._ensureTransformerNames = function (type, rawKeys) {
var keys = [];
for (var i = 0; i < rawKeys.length; i++) {
var key = rawKeys[i];
var deprecatedKey = transform.deprecatedTransformerMap[key];
if (deprecatedKey) {
// deprecated key, remap it to the new one
console.error(
"The transformer " + key + " has been renamed to " + deprecatedKey +
" in v3.0.0 - backwards compatibilty will be removed 4.0.0"
);
rawKeys.push(deprecatedKey);
} else if (transform.transformers[key]) {
// valid key
keys.push(key);
} else if (transform.namespaces[key]) {
// namespace, append all transformers within this namespace
keys = keys.concat(transform.namespaces[key]);
} else {
// invalid key
throw new ReferenceError(
"Unknown transformer " + key + " specified in " + type + " - " +
"transformer key names have been changed in 3.0.0 see " +
"the changelog for more info " +
"https://github.com/6to5/6to5/blob/master/CHANGELOG.md#300"
);
}
}
return keys;
};
transform.transformers = {};
transform.transformers = object();
transform.namespaces = object();
transform.moduleFormatters = {
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")
};
transform.deprecatedTransformerMap = require("./transformers/deprecated");
transform.moduleFormatters = require("./modules");
_.each({
specNoForInOfAssignment: require("./transformers/spec-no-for-in-of-assignment"),
specSetters: require("./transformers/spec-setters"),
var rawTransformers = require("./transformers");
// playground
methodBinding: require("./transformers/playground-method-binding"),
memoizationOperator: require("./transformers/playground-memoization-operator"),
objectGetterMemoization: require("./transformers/playground-object-getter-memoization"),
_.each(rawTransformers, function (transformer, key) {
var namespace = key.split(".")[0];
transform.namespaces[namespace] = transform.namespaces[namespace] || [];
transform.namespaces[namespace].push(key);
asyncToGenerator: require("./transformers/optional-async-to-generator"),
bluebirdCoroutines: require("./transformers/optional-bluebird-coroutines"),
react: require("./transformers/react"),
modules: require("./transformers/es6-modules"),
propertyNameShorthand: require("./transformers/es6-property-name-shorthand"),
arrayComprehension: require("./transformers/es7-array-comprehension"),
generatorComprehension: require("./transformers/es7-generator-comprehension"),
arrowFunctions: require("./transformers/es6-arrow-functions"),
classes: require("./transformers/es6-classes"),
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"),
unicodeRegex: require("./transformers/es6-unicode-regex"),
abstractReferences: require("./transformers/es7-abstract-references"),
constants: require("./transformers/es6-constants"),
letScoping: require("./transformers/es6-let-scoping"),
_blockHoist: require("./transformers/_block-hoist"),
generators: require("./transformers/es6-generators"),
restParameters: require("./transformers/es6-rest-parameters"),
protoToAssign: require("./transformers/optional-proto-to-assign"),
_declarations: require("./transformers/_declarations"),
// wrap up
useStrict: require("./transformers/use-strict"),
_aliasFunctions: require("./transformers/_alias-functions"),
_moduleFormatter: require("./transformers/_module-formatter"),
typeofSymbol: require("./transformers/optional-typeof-symbol"),
coreAliasing: require("./transformers/optional-core-aliasing"),
undefinedToVoid: require("./transformers/optional-undefined-to-void"),
// spec
specPropertyLiterals: require("./transformers/spec-property-literals"),
specMemberExpressionLiterals: require("./transformers/spec-member-expression-literals")
}, function (transformer, key) {
transform.transformers[key] = new Transformer(key, transformer);
});

View File

@@ -0,0 +1,69 @@
module.exports = TransformerPass;
var traverse = require("../traverse");
var _ = require("lodash");
/**
* This class is responsible for traversing over the provided `File`s
* AST and running it's parent transformers handlers over it.
*/
function TransformerPass(file, transformer) {
this.transformer = transformer;
this.handlers = transformer.handlers;
this.file = file;
}
TransformerPass.prototype.astRun = function (key) {
var handlers = this.handlers;
var file = this.file;
if (handlers.ast && handlers.ast[key]) {
handlers.ast[key](file.ast, file);
}
};
TransformerPass.prototype.canRun = function () {
var transformer = this.transformer;
var opts = this.file.opts;
var key = transformer.key;
if (key[0] === "_") return true;
var blacklist = opts.blacklist;
if (blacklist.length && _.contains(blacklist, key)) return false;
var whitelist = opts.whitelist;
if (whitelist.length && !_.contains(whitelist, key)) return false;
if (transformer.optional && !_.contains(opts.optional, key)) return false;
if (transformer.experimental && !opts.experimental) return false;
return true;
};
var transformVisitor = {
enter: function (node, parent, scope, context, state) {
var fns = state.handlers[node.type];
if (!fns) return;
return fns.enter(node, parent, scope, context, state.file, state.pass);
},
exit: function (node, parent, scope, context, state) {
var fns = state.handlers[node.type];
if (!fns) return;
return fns.exit(node, parent, scope, context, state.file, state.pass);
}
};
TransformerPass.prototype.transform = function () {
var file = this.file;
this.astRun("before");
var state = { file: file, handlers: this.handlers, pass: this };
traverse(file.ast, transformVisitor, file.scope, state);
this.astRun("after");
};

View File

@@ -1,15 +1,23 @@
"use strict";
module.exports = Transformer;
var traverse = require("../traverse");
var t = require("../types");
var _ = require("lodash");
var TransformerPass = require("./transformer-pass");
var t = require("../types");
var _ = require("lodash");
/**
* This is the class responsible for normalising a transformers handlers
* as well as constructing a `TransformerPass` that is repsonsible for
* actually running the transformer over the provided `File`.
*/
function Transformer(key, transformer, opts) {
this.manipulateOptions = transformer.manipulateOptions;
this.experimental = !!transformer.experimental;
this.secondPass = !!transformer.secondPass;
this.transformer = this.normalise(transformer);
this.optional = !!transformer.optional;
this.handlers = this.normalise(transformer);
this.opts = opts || {};
this.key = key;
}
@@ -32,6 +40,9 @@ Transformer.prototype.normalise = function (transformer) {
if (!_.isObject(fns)) return;
if (!fns.enter) fns.enter = _.noop;
if (!fns.exit) fns.exit = _.noop;
transformer[type] = fns;
var aliases = t.FLIPPED_ALIAS_KEYS[type];
@@ -45,54 +56,6 @@ Transformer.prototype.normalise = function (transformer) {
return transformer;
};
Transformer.prototype.astRun = function (file, key) {
var transformer = this.transformer;
if (transformer.ast && transformer.ast[key]) {
transformer.ast[key](file.ast, file);
}
};
Transformer.prototype.transform = function (file) {
var transformer = this.transformer;
var build = function (exit) {
return function (node, parent, scope) {
var fns = transformer[node.type];
if (!fns) return;
var fn = fns.enter;
if (exit) fn = fns.exit;
if (!fn) return;
return fn.call(this, node, parent, file, scope);
};
};
this.astRun(file, "before");
traverse(file.ast, {
enter: build(),
exit: build(true)
});
this.astRun(file, "after");
};
Transformer.prototype.canRun = function (file) {
var opts = file.opts;
var key = this.key;
if (key[0] === "_") return true;
var blacklist = opts.blacklist;
if (blacklist.length && _.contains(blacklist, key)) return false;
var whitelist = opts.whitelist;
if (whitelist.length && !_.contains(whitelist, key)) return false;
if (this.optional && !_.contains(opts.optional, key)) return false;
if (this.experimental && !opts.experimental) return false;
return true;
Transformer.prototype.buildPass = function (file) {
return new TransformerPass(file, this);
};

View File

@@ -1,86 +0,0 @@
var traverse = require("../../traverse");
var t = require("../../types");
var go = function (getBody, node, file, scope) {
var argumentsId;
var thisId;
var getArgumentsId = function () {
return argumentsId = argumentsId || file.generateUidIdentifier("arguments", scope);
};
var getThisId = function () {
return thisId = thisId || file.generateUidIdentifier("this", scope);
};
// traverse the function and find all alias functions so we can alias
// `arguments` and `this` if necessary
traverse(node, {
enter: function (node) {
if (!node._aliasFunction) {
if (t.isFunction(node)) {
// stop traversal of this node as it'll be hit again by this transformer
return this.skip();
} else {
return;
}
}
// traverse all child nodes of this function and find `arguments` and `this`
traverse(node, {
enter: function (node, parent) {
if (t.isFunction(node) && !node._aliasFunction) {
return this.skip();
}
if (node._ignoreAliasFunctions) return this.skip();
var getId;
if (t.isIdentifier(node) && node.name === "arguments") {
getId = getArgumentsId;
} else if (t.isThisExpression(node)) {
getId = getThisId;
} else {
return;
}
if (t.isReferenced(node, parent)) return getId();
}
});
return this.skip();
}
});
var body;
var pushDeclaration = function (id, init) {
body = body || getBody();
body.unshift(t.variableDeclaration("var", [
t.variableDeclarator(id, init)
]));
};
if (argumentsId) {
pushDeclaration(argumentsId, t.identifier("arguments"));
}
if (thisId) {
pushDeclaration(thisId, t.thisExpression());
}
};
exports.Program = function (node, parent, file, scope) {
go(function () {
return node.body;
}, node, file, scope);
};
exports.FunctionDeclaration =
exports.FunctionExpression = function (node, parent, file, scope) {
go(function () {
t.ensureBlock(node);
return node.body.body;
}, node, file, scope);
};

View File

@@ -1,11 +0,0 @@
var transform = require("../transform");
exports.ast = {
exit: function (ast, file) {
if (!transform.transformers.modules.canRun(file)) return;
if (file.moduleFormatter.transform) {
file.moduleFormatter.transform(ast);
}
}
};

View File

@@ -0,0 +1,38 @@
{
"specNoForInOfAssignment": "validation.noForInOfAssignment",
"specSetters": "validation.setters",
"specBlockScopedFunctions": "spec.blockScopedFunctions",
"malletOperator": "playground.malletOperator",
"methodBinding": "playground.methodBinding",
"memoizationOperator": "playground.memoizationOperator",
"objectGetterMemoization": "playground.objectGetterMemoization",
"modules": "es6.modules",
"propertyNameShorthand": "es6.properties.shorthand",
"arrayComprehension": "es7.comprehensions",
"generatorComprehension": "es7.comprehensions",
"arrowFunctions": "es6.arrowFunctions",
"classes": "es6.classes",
"objectSpread": "es7.objectSpread",
"exponentiationOperator": "es7.exponentiationOperator",
"spread": "es6.spread",
"templateLiterals": "es6.templateLiterals",
"propertyMethodAssignment": "es6.properties.shorthand",
"computedPropertyNames": "es6.properties.computed",
"defaultParameters": "es6.parameters.default",
"restParameters": "es6.parameters.rest",
"destructuring": "es6.destructuring",
"forOf": "es6.forOf",
"unicodeRegex": "es6.unicodeRegex",
"abstractReferences": "es7.abstractReferences",
"constants": "es6.constants",
"letScoping": "es6.letScoping",
"blockScopingTDZ": "es6.blockScopingTDZ",
"generators": "regenerator",
"protoToAssign": "spec.protoToAssign",
"typeofSymbol": "spec.typeofSymbol",
"coreAliasing": "selfContained",
"undefinedToVoid": "spec.undefinedToVoid",
"undeclaredVariableCheck": "validation.undeclaredVariableCheck",
"specPropertyLiterals": "minification.propertyLiterals",
"specMemberExpressionLiterals": "minification.memberExpressionLiterals"
}

View File

@@ -0,0 +1,26 @@
"use strict";
var util = require("../../../util");
var t = require("../../../types");
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.computed, prop.value);
return false;
} else {
return true;
}
});
if (!hasAny) return;
return t.callExpression(
t.memberExpression(t.identifier("Object"), t.identifier("defineProperties")),
[node, util.buildDefineProperties(mutatorMap)]
);
};

View File

@@ -1,436 +0,0 @@
var propertyMethodAssignment = require("./es6-property-method-assignment");
var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
exports.ClassDeclaration = function (node, parent, file, scope) {
return new Class(node, file, scope, true).run();
};
exports.ClassExpression = function (node, parent, file, scope) {
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)) {
node.id = parent.id;
}
}
return new Class(node, file, scope, false).run();
};
/**
* Description
*
* @param {Node} node
* @param {File} file
* @param {Scope} scope
* @param {Boolean} closure
*/
function Class(node, file, scope, isStatement) {
this.isStatement = isStatement;
this.scope = scope;
this.node = node;
this.file = file;
this.hasInstanceMutators = false;
this.hasStaticMutators = false;
this.instanceMutatorMap = {};
this.staticMutatorMap = {};
this.hasConstructor = false;
this.className = node.id || file.generateUidIdentifier("class", scope);
this.superName = node.superClass;
this.isLoose = file.isLoose("classes");
}
/**
* Description
*
* @returns {Array}
*/
Class.prototype.run = function () {
var superName = this.superName;
var className = this.className;
var file = this.file;
//
var body = this.body = [];
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;
var closureParams = [];
var closureArgs = [];
//
if (superName) {
closureArgs.push(superName);
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])));
}
this.buildBody();
t.inheritsComments(body[0], this.node);
var init;
if (body.length === 1) {
// only a constructor so no need for a closure container
init = t.toExpression(constructor);
} else {
body.push(t.returnStatement(className));
init = t.callExpression(
t.functionExpression(null, closureParams, t.blockStatement(body)),
closureArgs
);
}
if (this.isStatement) {
return t.variableDeclaration("let", [
t.variableDeclarator(className, init)
]);
} else {
return init;
}
};
/**
* Description
*/
Class.prototype.buildBody = function () {
var constructor = this.constructor;
var className = this.className;
var superName = this.superName;
var classBody = this.node.body.body;
var body = this.body;
for (var i in classBody) {
var node = classBody[i];
if (t.isMethodDefinition(node)) {
this.replaceInstanceSuperReferences(node);
if (node.key.name === "constructor") {
this.pushConstructor(node);
} else {
this.pushMethod(node);
}
} else if (t.isPrivateDeclaration(node)) {
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)) {
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));
}
var instanceProps;
var staticProps;
if (this.hasInstanceMutators) {
instanceProps = util.buildDefineProperties(this.instanceMutatorMap);
}
if (this.hasStaticMutators) {
staticProps = util.buildDefineProperties(this.staticMutatorMap);
}
if (instanceProps || staticProps) {
staticProps = staticProps || t.literal(null);
var args = [className, staticProps];
if (instanceProps) args.push(instanceProps);
body.push(t.expressionStatement(
t.callExpression(this.file.addHelper("prototype-properties"), args)
));
}
};
/**
* Push a method to it's respective mutatorMap.
*
* @param {Node} node MethodDefinition
*/
Class.prototype.pushMethod = function (node) {
var methodName = node.key;
var kind = node.kind;
if (kind === "") {
propertyMethodAssignment._namedMethod(node, this.file, this.scope);
if (this.isLoose) {
// use assignments instead of define properties for loose classes
var className = this.className;
if (!node.static) className = t.memberExpression(className, t.identifier("prototype"));
methodName = t.memberExpression(className, methodName, node.computed);
var expr = t.expressionStatement(t.assignmentExpression("=", methodName, node.value));
t.inheritsComments(expr, node);
this.body.push(expr);
return;
}
kind = "value";
}
var mutatorMap = this.instanceMutatorMap;
if (node.static) {
this.hasStaticMutators = true;
mutatorMap = this.staticMutatorMap;
} else {
this.hasInstanceMutators = true;
}
util.pushMutatorMap(mutatorMap, methodName, kind, node.computed, node);
};
/**
* Gets a node representing the super class value of the named property.
*
* @example
*
* _get(Object.getPrototypeOf(CLASS.prototype), "METHOD", this)
*
* @param {Node} property
* @param {boolean} isStatic
* @param {boolean} isComputed
*
* @returns {Node}
*/
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");
if (parent.property === id) {
return;
} else if (t.isCallExpression(parent, { callee: id })) {
// super(); -> ClassName.prototype.MethodName.call(this);
parent.arguments.unshift(t.thisExpression());
if (methodName.name === "constructor") {
// constructor() { super(); }
return t.memberExpression(superName, t.identifier("call"));
} else {
id = superName;
// foo() { super(); }
if (!methodNode.static) {
id = t.memberExpression(id, t.identifier("prototype"));
}
id = t.memberExpression(id, methodName, methodNode.computed);
return t.memberExpression(id, t.identifier("call"));
}
} else if (t.isMemberExpression(parent) && !methodNode.static) {
// super.test -> ClassName.prototype.test
return t.memberExpression(superName, t.identifier("prototype"));
} else {
return superName;
}
};
/**
* Replace all `super` references with a reference to our `superClass`.
*
* @param {Node} methodNode MethodDefinition
*/
Class.prototype.replaceInstanceSuperReferences = function (methodNode) {
var method = methodNode.value;
var self = this;
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();
}
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(); -> _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;
}
}
};
/**
* Replace the constructor body of our class.
*
* @param {Node} method MethodDefinition
*/
Class.prototype.pushConstructor = function (method) {
if (method.kind) {
throw this.file.errorWithNode(method, "illegal kind for constructor method");
}
var construct = this.constructor;
var fn = method.value;
this.hasConstructor = true;
t.inherits(construct, fn);
t.inheritsComments(construct, method);
construct._ignoreUserWhitespace = true;
construct.defaults = fn.defaults;
construct.params = fn.params;
construct.body = fn.body;
construct.rest = fn.rest;
};

View File

@@ -1,82 +0,0 @@
var traverse = require("../../traverse");
var t = require("../../types");
var _ = require("lodash");
exports.Program =
exports.BlockStatement =
exports.ForInStatement =
exports.ForOfStatement =
exports.ForStatement = function (node, parent, file) {
var hasConstants = false;
var constants = {};
/**
* Check the results of `util.getIds` as `names` generated from a
* node against it's parent.
*/
var check = function (parent, names, scope) {
for (var name in names) {
var nameNode = names[name];
if (!_.has(constants, name)) continue;
if (parent && t.isBlockStatement(parent) && parent !== constants[name]) continue;
if (scope) {
var defined = scope.get(name);
if (defined && defined === nameNode) continue;
}
throw file.errorWithNode(nameNode, name + " is read-only");
}
};
var getIds = function (node) {
return t.getIds(node, true, ["MemberExpression"]);
};
/**
* Collect all constants in this scope.
*/
_.each(node.body, function (child, parent) {
if (t.isExportDeclaration(child)) {
child = child.declaration;
}
if (t.isVariableDeclaration(child, { kind: "const" })) {
for (var i in child.declarations) {
var declar = child.declarations[i];
var ids = getIds(declar);
for (var name in ids) {
var nameNode = ids[name];
var names = {};
names[name] = nameNode;
check(parent, names);
constants[name] = parent;
hasConstants = true;
}
declar._ignoreConstant = true;
}
child._ignoreConstant = true;
child.kind = "let";
}
});
if (!hasConstants) return;
traverse(node, {
enter: function (child, parent, scope) {
if (child._ignoreConstant) return;
if (t.isVariableDeclaration(child)) return;
if (t.isVariableDeclarator(child) || t.isDeclaration(child) || t.isAssignmentExpression(child)) {
check(parent, getIds(child), scope);
}
}
});
};

View File

@@ -1,91 +0,0 @@
var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
exports.Function = function (node, parent, file, scope) {
if (!node.defaults || !node.defaults.length) return;
t.ensureBlock(node);
var ids = node.params.map(function (param) {
return t.getIds(param);
});
var iife = false;
var i;
var def;
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 (i in node.defaults) {
def = node.defaults[i];
if (!def) continue;
var param = node.params[i];
// temporal dead zone check - here we prevent accessing of params that
// are to the right - ie. uninitialized parameters
var rightIds = ids.slice(i);
for (i in rightIds) {
checkTDZ(rightIds[i]);
}
// we're accessing a variable that's already defined within this function
var has = scope.get(param.name, true);
if (has && node.params.indexOf(has) < 0) {
iife = true;
}
}
var body = [];
var argsIdentifier = t.identifier("arguments");
argsIdentifier._ignoreAliasFunctions = true;
var lastNonDefaultParam = 0;
for (i in node.defaults) {
def = node.defaults[i];
if (!def) {
lastNonDefaultParam = +i + 1;
continue;
}
body.push(util.template("default-parameter", {
VARIABLE_NAME: node.params[i],
DEFAULT_VALUE: def,
ARGUMENT_KEY: t.literal(+i),
ARGUMENTS: argsIdentifier
}, true));
}
// we need to cut off all trailing default parameters
node.params = node.params.slice(0, lastNonDefaultParam);
if (iife) {
var container = t.functionExpression(null, [], node.body, node.generator);
container._aliasFunction = true;
body.push(t.returnStatement(t.callExpression(container, [])));
node.body = t.blockStatement(body);
} else {
node.body.body = body.concat(node.body.body);
}
node.defaults = [];
};

View File

@@ -1,497 +0,0 @@
var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
var _ = require("lodash");
var isLet = function (node, parent) {
if (!t.isVariableDeclaration(node)) return false;
if (node._let) return true;
if (node.kind !== "let") return false;
// https://github.com/6to5/6to5/issues/255
if (!t.isFor(parent) || t.isFor(parent) && parent.left !== node) {
_.each(node.declarations, function (declar) {
declar.init = declar.init || t.identifier("undefined");
});
}
node._let = true;
node.kind = "var";
return true;
};
var isVar = function (node, parent) {
return t.isVariableDeclaration(node, { kind: "var" }) && !isLet(node, parent);
};
var standardiseLets = function (declars) {
for (var i in declars) {
delete declars[i]._let;
}
};
exports.VariableDeclaration = function (node, parent) {
isLet(node, parent);
};
exports.Loop = function (node, parent, file, scope) {
var init = node.left || node.init;
if (isLet(init, node)) {
t.ensureBlock(node);
node.body._letDeclars = [init];
}
if (t.isLabeledStatement(parent)) {
// set label so `run` has access to it
node.label = parent.label;
}
var letScoping = new LetScoping(node, node.body, parent, file, scope);
letScoping.run();
if (node.label && !t.isLabeledStatement(parent)) {
// we've been given a label so let's wrap ourselves
return t.labeledStatement(node.label, node);
}
};
exports.BlockStatement = function (block, parent, file, scope) {
if (!t.isLoop(parent)) {
var letScoping = new LetScoping(false, block, parent, file, scope);
letScoping.run();
}
};
/**
* Description
*
* @param {Boolean|Node} loopParent
* @param {Node} block
* @param {Node} parent
* @param {File} file
* @param {Scope} scope
*/
function LetScoping(loopParent, block, parent, file, scope) {
this.loopParent = loopParent;
this.parent = parent;
this.scope = scope;
this.block = block;
this.file = file;
this.letReferences = {};
this.body = [];
}
/**
* Start the ball rolling.
*/
LetScoping.prototype.run = function () {
var block = this.block;
if (block._letDone) return;
block._letDone = true;
this.info = this.getInfo();
// remap all let references that exist in upper scopes to their uid
this.remap();
// this is a block within a `Function` so we can safely leave it be
if (t.isFunction(this.parent)) return this.noClosure();
// this block has no let references so let's clean up
if (!this.info.keys.length) return this.noClosure();
// returns whether or not there are any outside let references within any
// functions
var referencesInClosure = this.getLetReferences();
// no need for a closure so let's clean up
if (!referencesInClosure) return this.noClosure();
// if we're inside of a for loop then we search to see if there are any
// `break`s, `continue`s, `return`s etc
this.has = this.checkLoop();
// hoist var references to retain scope
this.hoistVarDeclarations();
// set let references to plain var references
standardiseLets(this.info.declarators);
// turn letReferences into an array
var letReferences = _.values(this.letReferences);
// build the closure that we're going to wrap the block with
var fn = t.functionExpression(null, letReferences, t.blockStatement(block.body));
fn._aliasFunction = true;
// replace the current block body with the one we're going to build
block.body = this.body;
// change upper scope references with their uid if they have one
var params = this.getParams(letReferences);
// build a call and a unique id that we can assign the return value to
var call = t.callExpression(fn, params);
var ret = this.file.generateUidIdentifier("ret", this.scope);
var hasYield = traverse.hasType(fn.body, "YieldExpression", t.FUNCTION_TYPES);
if (hasYield) {
fn.generator = true;
call = t.yieldExpression(call, true);
}
this.build(ret, call);
};
/**
* There are no let references accessed within a closure so we can just turn the
* lets into vars.
*/
LetScoping.prototype.noClosure = function () {
standardiseLets(this.info.declarators);
};
/**
* Traverse through block and replace all references that exist in a higher
* scope to their uids.
*/
LetScoping.prototype.remap = function () {
var replacements = this.info.duplicates;
var block = this.block;
if (!this.info.hasDuplicates) return;
var replace = function (node, parent, scope) {
if (!t.isIdentifier(node)) return;
if (!t.isReferenced(node, parent)) return;
if (scope && scope.hasOwn(node.name)) return;
node.name = replacements[node.name] || node.name;
};
var traverseReplace = function (node, parent) {
replace(node, parent);
traverse(node, { enter: replace });
};
var loopParent = this.loopParent;
if (loopParent) {
traverseReplace(loopParent.right, loopParent);
traverseReplace(loopParent.test, loopParent);
traverseReplace(loopParent.update, loopParent);
}
traverse(block, { enter: replace });
};
/**
* Description
*
* @returns {Object}
*/
LetScoping.prototype.getInfo = function () {
var block = this.block;
var scope = this.scope;
var file = this.file;
var opts = {
// array of `Identifier` names of let variables that appear lexically out of
// this scope but should be accessible - eg. `ForOfStatement`.left
outsideKeys: [],
// array of let `VariableDeclarator`s that are a part of this block
declarators: block._letDeclars || [],
// object of duplicate ids and their aliases - if there's an `Identifier`
// name that's used in an upper scope we generate a unique id and replace
// all references with it
duplicates: {},
hasDuplicates: false,
// array of `Identifier` names of let variables that are accessible within
// the current block
keys: []
};
var duplicates = function (id, key) {
var has = scope.parentGet(key);
if (has && has !== id) {
// there's a variable with this exact name in an upper scope so we need
// to generate a new name
opts.duplicates[key] = id.name = file.generateUid(key, scope);
opts.hasDuplicates = true;
}
};
var i;
var declar;
for (i in opts.declarators) {
declar = opts.declarators[i];
opts.declarators.push(declar);
var keys = t.getIds(declar, true);
_.each(keys, duplicates);
keys = Object.keys(keys);
opts.outsideKeys = opts.outsideKeys.concat(keys);
opts.keys = opts.keys.concat(keys);
}
for (i in block.body) {
declar = block.body[i];
if (!isLet(declar, block)) continue;
var declars = t.getIds(declar, true);
for (var key in declars) {
duplicates(declars[key], key);
opts.keys.push(key);
}
}
return opts;
};
/**
* If we're inside of a loop then traverse it and check if it has one of
* the following node types `ReturnStatement`, `BreakStatement`,
* `ContinueStatement` and replace it with a return value that we can track
* later on.
*
* @returns {Object}
*/
LetScoping.prototype.checkLoop = function () {
var has = {
hasContinue: false,
hasReturn: false,
hasBreak: false,
};
traverse(this.block, {
enter: function (node, parent) {
var replace;
if (t.isFunction(node) || t.isLoop(node)) {
return this.skip();
}
if (node && !node.label) {
if (t.isBreakStatement(node)) {
if (t.isSwitchCase(parent)) return;
has.hasBreak = true;
replace = t.returnStatement(t.literal("break"));
} else if (t.isContinueStatement(node)) {
has.hasContinue = true;
replace = t.returnStatement(t.literal("continue"));
}
}
if (t.isReturnStatement(node)) {
has.hasReturn = true;
replace = t.returnStatement(t.objectExpression([
t.property("init", t.identifier("v"), node.argument || t.identifier("undefined"))
]));
}
if (replace) return t.inherits(replace, node);
}
});
return has;
};
/**
* Hoist all var declarations in this block to before it so they retain scope
* once we wrap everything in a closure.
*/
LetScoping.prototype.hoistVarDeclarations = function () {
var self = this;
traverse(this.block, {
enter: function (node, parent) {
if (t.isForStatement(node)) {
if (isVar(node.init, node)) {
node.init = t.sequenceExpression(self.pushDeclar(node.init));
}
} else if (t.isFor(node)) {
if (isVar(node.left, node)) {
node.left = node.left.declarations[0].id;
}
} else if (isVar(node, parent)) {
return self.pushDeclar(node).map(t.expressionStatement);
} else if (t.isFunction(node)) {
return this.skip();
}
}
});
};
/**
* Build up a parameter list that we'll call our closure wrapper with, replacing
* all duplicate ids with their uid.
*
* @param {Array} params
* @returns {Array}
*/
LetScoping.prototype.getParams = function (params) {
var info = this.info;
params = _.cloneDeep(params);
_.each(params, function (param) {
param.name = info.duplicates[param.name] || param.name;
});
return params;
};
/**
* Get all let references within this block. Stopping whenever we reach another
* block.
*/
LetScoping.prototype.getLetReferences = function () {
var closurify = false;
var self = this;
// traverse through this block, stopping on functions and checking if they
// contain any outside let references
traverse(this.block, {
enter: function (node, parent, scope) {
if (t.isFunction(node)) {
traverse(node, {
enter: function (node, parent) {
// not an identifier so we have no use
if (!t.isIdentifier(node)) return;
// not a direct reference
if (!t.isReferenced(node, parent)) return;
// this scope has a variable with the same name so it couldn't belong
// to our let scope
if (scope.hasOwn(node.name, true)) return;
closurify = true;
// this key doesn't appear just outside our scope
if (!_.contains(self.info.outsideKeys, node.name)) return;
// push this badboy
self.letReferences[node.name] = node;
}
});
return this.skip();
}
}
});
return closurify;
};
/**
* Turn a `VariableDeclaration` into an array of `AssignmentExpressions` with
* their declarations hoisted to before the closure wrapper.
*
* @param {Node} node VariableDeclaration
* @returns {Array}
*/
LetScoping.prototype.pushDeclar = function (node) {
this.body.push(t.variableDeclaration(node.kind, node.declarations.map(function (declar) {
return t.variableDeclarator(declar.id);
})));
var replace = [];
for (var i in node.declarations) {
var declar = node.declarations[i];
if (!declar.init) continue;
var expr = t.assignmentExpression("=", declar.id, declar.init);
replace.push(t.inherits(expr, declar));
}
return replace;
};
/**
* Push the closure to the body.
*
* @param {Node} ret Identifier
* @param {Node} call CallExpression
*/
LetScoping.prototype.build = function (ret, call) {
var has = this.has;
if (has.hasReturn || has.hasBreak || has.hasContinue) {
this.buildHas(ret, call);
} else {
this.body.push(t.expressionStatement(call));
}
};
/**
* Description
*
* @param {Node} ret Identifier
* @param {Node} call CallExpression
*/
LetScoping.prototype.buildHas = function (ret, call) {
var body = this.body;
body.push(t.variableDeclaration("var", [
t.variableDeclarator(ret, call)
]));
var loopParent = this.loopParent;
var retCheck;
var has = this.has;
var cases = [];
if (has.hasReturn) {
// typeof ret === "object"
retCheck = util.template("let-scoping-return", {
RETURN: ret
});
}
if (has.hasBreak || has.hasContinue) {
// ensure that the parent has a label as we're building a switch and we
// need to be able to access it
var label = loopParent.label = loopParent.label || this.file.generateUidIdentifier("loop", this.scope);
if (has.hasBreak) {
cases.push(t.switchCase(t.literal("break"), [t.breakStatement(label)]));
}
if (has.hasContinue) {
cases.push(t.switchCase(t.literal("continue"), [t.continueStatement(label)]));
}
if (has.hasReturn) {
cases.push(t.switchCase(null, [retCheck]));
}
if (cases.length === 1) {
var single = cases[0];
body.push(t.ifStatement(
t.binaryExpression("===", ret, single.test),
single.consequent[0]
));
} else {
body.push(t.switchStatement(ret, cases));
}
} else {
if (has.hasReturn) body.push(retCheck);
}
};

View File

@@ -1,73 +0,0 @@
var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
exports._namedMethod = 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;
}
};
exports.Property = function (node, parent, file, scope) {
if (!node.method) return;
node.method = false;
exports._namedMethod(node, 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.computed, prop.value);
return false;
} else {
return true;
}
});
if (!hasAny) return;
return t.callExpression(
t.memberExpression(t.identifier("Object"), t.identifier("defineProperties")),
[node, util.buildDefineProperties(mutatorMap)]
);
};

View File

@@ -1,8 +0,0 @@
var t = require("../../types");
var _ = require("lodash");
exports.Property = function (node) {
if (!node.shorthand) return;
node.shorthand = false;
node.key = t.removeComments(_.clone(node.key));
};

View File

@@ -1,36 +0,0 @@
var util = require("../../util");
var t = require("../../types");
exports.Function = function (node, parent, file) {
if (!node.rest) return;
var rest = node.rest;
delete node.rest;
t.ensureBlock(node);
var argsId = t.identifier("arguments");
argsId._ignoreAliasFunctions = true;
var start = t.literal(node.params.length);
var key = file.generateUidIdentifier("key");
var arrKey = key;
if (node.params.length) {
arrKey = t.binaryExpression("-", arrKey, start);
}
node.body.body.unshift(
t.variableDeclaration("var", [
t.variableDeclarator(rest, t.arrayExpression([]))
]),
util.template("rest", {
ARGUMENTS: argsId,
ARRAY_KEY: arrKey,
START: start,
ARRAY: rest,
KEY: key
})
);
};

View File

@@ -1,4 +1,6 @@
var t = require("../../types");
"use strict";
var t = require("../../../types");
exports.ArrowFunctionExpression = function (node) {
t.ensureBlock(node);

View File

@@ -0,0 +1,50 @@
"use strict";
var traverse = require("../../../traverse");
var t = require("../../../types");
var visitor = {
enter: function (node, parent, scope, context, state) {
if (!t.isReferencedIdentifier(node, parent)) return;
var declared = state.letRefs[node.name];
if (!declared) return;
// declared node is different in this scope
if (scope.get(node.name, true) !== declared) return;
var declaredLoc = declared.loc;
var referenceLoc = node.loc;
if (!declaredLoc || !referenceLoc) return;
// does this reference appear on a line before the declaration?
var before = referenceLoc.start.line < declaredLoc.start.line;
if (referenceLoc.start.line === declaredLoc.start.line) {
// this reference appears on the same line
// check it appears before the declaration
before = referenceLoc.start.col < declaredLoc.start.col;
}
if (before) {
throw state.file.errorWithNode(node, "Temporal dead zone - accessing a variable before it's initialized");
}
}
};
exports.optional = true;
exports.Loop =
exports.Program =
exports.BlockStatement = function (node, parent, scope, context, file) {
var letRefs = node._letReferences;
if (!letRefs) return;
var state = {
letRefs: letRefs,
file: file
};
traverse(node, visitor, scope, state);
};

View File

@@ -0,0 +1,491 @@
"use strict";
var traverse = require("../../../traverse");
var object = require("../../../helpers/object");
var util = require("../../../util");
var t = require("../../../types");
var _ = require("lodash");
var isLet = function (node, parent) {
if (!t.isVariableDeclaration(node)) return false;
if (node._let) return true;
if (node.kind !== "let") return false;
// https://github.com/6to5/6to5/issues/255
if (!t.isFor(parent) || t.isFor(parent) && parent.left !== node) {
for (var i = 0; i < node.declarations.length; i++) {
var declar = node.declarations[i];
declar.init = declar.init || t.identifier("undefined");
}
}
node._let = true;
node.kind = "var";
return true;
};
var isVar = function (node, parent) {
return t.isVariableDeclaration(node, { kind: "var" }) && !isLet(node, parent);
};
var standardiseLets = function (declars) {
for (var i = 0; i < declars.length; i++) {
delete declars[i]._let;
}
};
exports.VariableDeclaration = function (node, parent) {
isLet(node, parent);
};
exports.Loop = function (node, parent, scope, context, file) {
var init = node.left || node.init;
if (isLet(init, node)) {
t.ensureBlock(node);
node.body._letDeclarators = [init];
}
if (t.isLabeledStatement(parent)) {
// set label so `run` has access to it
node.label = parent.label;
}
var letScoping = new LetScoping(node, node.body, parent, scope, file);
letScoping.run();
if (node.label && !t.isLabeledStatement(parent)) {
// we've been given a label so let's wrap ourselves
return t.labeledStatement(node.label, node);
}
};
exports.Program =
exports.BlockStatement = function (block, parent, scope, context, file) {
if (!t.isLoop(parent)) {
var letScoping = new LetScoping(false, block, parent, scope, file);
letScoping.run();
}
};
/**
* Description
*
* @param {Boolean|Node} loopParent
* @param {Node} block
* @param {Node} parent
* @param {Scope} scope
* @param {File} file
*/
function LetScoping(loopParent, block, parent, scope, file) {
this.loopParent = loopParent;
this.parent = parent;
this.scope = scope;
this.block = block;
this.file = file;
this.outsideLetReferences = object();
this.hasLetReferences = false;
this.letReferences = block._letReferences = object();
this.body = [];
}
/**
* Start the ball rolling.
*/
LetScoping.prototype.run = function () {
var block = this.block;
if (block._letDone) return;
block._letDone = true;
var needsClosure = this.getLetReferences();
// this is a block within a `Function/Program` so we can safely leave it be
if (t.isFunction(this.parent) || t.isProgram(this.block)) return;
// we can skip everything
if (!this.hasLetReferences) return;
if (needsClosure) {
this.needsClosure();
} else {
this.remap();
}
};
function replace(node, parent, scope, context, remaps) {
if (!t.isReferencedIdentifier(node, parent)) return;
var remap = remaps[node.name];
if (!remap) return;
var own = scope.get(node.name, true);
if (own === remap.node) {
node.name = remap.uid;
} else {
// scope already has it's own declaration that doesn't
// match the one we have a stored replacement for
if (context) context.skip();
}
}
var replaceVisitor = {
enter: replace
};
function traverseReplace(node, parent, scope, remaps) {
replace(node, parent, scope, null, remaps);
traverse(node, replaceVisitor, scope, remaps);
}
/**
* Description
*/
LetScoping.prototype.remap = function () {
var hasRemaps = false;
var letRefs = this.letReferences;
var scope = this.scope;
// alright, so since we aren't wrapping this block in a closure
// we have to check if any of our let variables collide with
// those in upper scopes and then if they do, generate a uid
// for them and replace all references with it
var remaps = object();
for (var key in letRefs) {
// just an Identifier node we collected in `getLetReferences`
// this is the defining identifier of a declaration
var ref = letRefs[key];
if (scope.parentHas(key)) {
var uid = scope.generateUidIdentifier(ref.name).name;
ref.name = uid;
hasRemaps = true;
remaps[key] = remaps[uid] = {
node: ref,
uid: uid
};
}
}
if (!hasRemaps) return;
//
var loopParent = this.loopParent;
if (loopParent) {
traverseReplace(loopParent.right, loopParent, scope, remaps);
traverseReplace(loopParent.test, loopParent, scope, remaps);
traverseReplace(loopParent.update, loopParent, scope, remaps);
}
traverse(this.block, replaceVisitor, scope, remaps);
};
/**
* Description
*/
LetScoping.prototype.needsClosure = function () {
var block = this.block;
// if we're inside of a for loop then we search to see if there are any
// `break`s, `continue`s, `return`s etc
this.has = this.checkLoop();
// hoist var references to retain scope
this.hoistVarDeclarations();
// turn outsideLetReferences into an array
var params = _.values(this.outsideLetReferences);
// build the closure that we're going to wrap the block with
var fn = t.functionExpression(null, params, t.blockStatement(block.body));
fn._aliasFunction = true;
// replace the current block body with the one we're going to build
block.body = this.body;
// build a call and a unique id that we can assign the return value to
var call = t.callExpression(fn, params);
var ret = this.scope.generateUidIdentifier("ret");
// handle generators
var hasYield = traverse.hasType(fn.body, this.scope, "YieldExpression", t.FUNCTION_TYPES);
if (hasYield) {
fn.generator = true;
call = t.yieldExpression(call, true);
}
// handlers async functions
var hasAsync = traverse.hasType(fn.body, this.scope, "AwaitExpression", t.FUNCTION_TYPES);
if (hasAsync) {
fn.async = true;
call = t.awaitExpression(call, true);
}
this.build(ret, call);
};
var letReferenceFunctionVisitor = {
enter: function (node, parent, scope, context, state) {
// not a direct reference
if (!t.isReferencedIdentifier(node, parent)) return;
// this scope has a variable with the same name so it couldn't belong
// to our let scope
if (scope.hasOwn(node.name, true)) return;
// not a part of our scope
if (!state.letReferences[node.name]) return;
state.closurify = true;
}
};
var letReferenceBlockVisitor = {
enter: function (node, parent, scope, context, state) {
if (t.isFunction(node)) {
traverse(node, letReferenceFunctionVisitor, scope, state);
return context.skip();
}
}
};
/**
* Description
*/
LetScoping.prototype.getLetReferences = function () {
var block = this.block;
var declarators = block._letDeclarators || [];
var declar;
//
for (var i = 0; i < declarators.length; i++) {
declar = declarators[i];
_.extend(this.outsideLetReferences, t.getIds(declar, true));
}
//
if (block.body) {
for (i = 0; i < block.body.length; i++) {
declar = block.body[i];
if (isLet(declar, block)) {
declarators = declarators.concat(declar.declarations);
}
}
}
//
for (i = 0; i < declarators.length; i++) {
declar = declarators[i];
var keys = t.getIds(declar, true);
_.extend(this.letReferences, keys);
this.hasLetReferences = true;
}
// no let references so we can just quit
if (!this.hasLetReferences) return;
// set let references to plain var references
standardiseLets(declarators);
var state = {
letReferences: this.letReferences,
closurify: false
};
// traverse through this block, stopping on functions and checking if they
// contain any local let references
traverse(this.block, letReferenceBlockVisitor, this.scope, state);
return state.closurify;
};
var loopVisitor = {
enter: function (node, parent, scope, context, state) {
var replace;
if (t.isFunction(node) || t.isLoop(node)) {
return context.skip();
}
if (node && !node.label && state.isLoop) {
if (t.isBreakStatement(node)) {
if (t.isSwitchCase(parent)) return;
state.hasBreak = true;
replace = t.returnStatement(t.literal("break"));
} else if (t.isContinueStatement(node)) {
state.hasContinue = true;
replace = t.returnStatement(t.literal("continue"));
}
}
if (t.isReturnStatement(node)) {
state.hasReturn = true;
replace = t.returnStatement(t.objectExpression([
t.property("init", t.identifier("v"), node.argument || t.identifier("undefined"))
]));
}
if (replace) return t.inherits(replace, node);
}
};
/**
* If we're inside of a loop then traverse it and check if it has one of
* the following node types `ReturnStatement`, `BreakStatement`,
* `ContinueStatement` and replace it with a return value that we can track
* later on.
*
* @returns {Object}
*/
LetScoping.prototype.checkLoop = function () {
var state = {
hasContinue: false,
hasReturn: false,
hasBreak: false,
isLoop: !!this.loopParent
};
traverse(this.block, loopVisitor, this.scope, state);
return state;
};
var hoistVarDeclarationsVisitor = {
enter: function (node, parent, scope, context, self) {
if (t.isForStatement(node)) {
if (isVar(node.init, node)) {
node.init = t.sequenceExpression(self.pushDeclar(node.init));
}
} else if (t.isFor(node)) {
if (isVar(node.left, node)) {
node.left = node.left.declarations[0].id;
}
} else if (isVar(node, parent)) {
return self.pushDeclar(node).map(t.expressionStatement);
} else if (t.isFunction(node)) {
return context.skip();
}
}
};
/**
* Hoist all var declarations in this block to before it so they retain scope
* once we wrap everything in a closure.
*/
LetScoping.prototype.hoistVarDeclarations = function () {
traverse(this.block, hoistVarDeclarationsVisitor, this.scope, this);
};
/**
* Turn a `VariableDeclaration` into an array of `AssignmentExpressions` with
* their declarations hoisted to before the closure wrapper.
*
* @param {Node} node VariableDeclaration
* @returns {Array}
*/
LetScoping.prototype.pushDeclar = function (node) {
this.body.push(t.variableDeclaration(node.kind, node.declarations.map(function (declar) {
return t.variableDeclarator(declar.id);
})));
var replace = [];
for (var i = 0; i < node.declarations.length; i++) {
var declar = node.declarations[i];
if (!declar.init) continue;
var expr = t.assignmentExpression("=", declar.id, declar.init);
replace.push(t.inherits(expr, declar));
}
return replace;
};
/**
* Push the closure to the body.
*
* @param {Node} ret Identifier
* @param {Node} call CallExpression
*/
LetScoping.prototype.build = function (ret, call) {
var has = this.has;
if (has.hasReturn || has.hasBreak || has.hasContinue) {
this.buildHas(ret, call);
} else {
this.body.push(t.expressionStatement(call));
}
};
/**
* Description
*
* @param {Node} ret Identifier
* @param {Node} call CallExpression
*/
LetScoping.prototype.buildHas = function (ret, call) {
var body = this.body;
body.push(t.variableDeclaration("var", [
t.variableDeclarator(ret, call)
]));
var loopParent = this.loopParent;
var retCheck;
var has = this.has;
var cases = [];
if (has.hasReturn) {
// typeof ret === "object"
retCheck = util.template("let-scoping-return", {
RETURN: ret
});
}
if (has.hasBreak || has.hasContinue) {
if (!loopParent) {
throw new Error("Has no loop parent but we're trying to reassign breaks " +
"and continues, something is going wrong here.");
}
// ensure that the parent has a label as we're building a switch and we
// need to be able to access it
var label = loopParent.label = loopParent.label || this.scope.generateUidIdentifier("loop");
if (has.hasBreak) {
cases.push(t.switchCase(t.literal("break"), [t.breakStatement(label)]));
}
if (has.hasContinue) {
cases.push(t.switchCase(t.literal("continue"), [t.continueStatement(label)]));
}
if (has.hasReturn) {
cases.push(t.switchCase(null, [retCheck]));
}
if (cases.length === 1) {
var single = cases[0];
body.push(t.ifStatement(
t.binaryExpression("===", ret, single.test),
single.consequent[0]
));
} else {
body.push(t.switchStatement(ret, cases));
}
} else {
if (has.hasReturn) body.push(retCheck);
}
};

View File

@@ -0,0 +1,258 @@
"use strict";
var ReplaceSupers = require("../../helpers/replace-supers");
var nameMethod = require("../../helpers/name-method");
var util = require("../../../util");
var t = require("../../../types");
exports.ClassDeclaration = function (node, parent, scope, context, file) {
return new Class(node, file, scope, true).run();
};
exports.ClassExpression = function (node, parent, scope, context, file) {
if (!node.id) {
if (t.isProperty(parent) && parent.value === node && !parent.computed && t.isIdentifier(parent.key)) {
// var o = { foo: class {} };
node.id = parent.key;
}
if (t.isVariableDeclarator(parent) && t.isIdentifier(parent.id)) {
// var foo = class {};
node.id = parent.id;
}
}
return new Class(node, file, scope, false).run();
};
/**
* Description
*
* @param {Node} node
* @param {File} file
* @param {Scope} scope
* @param {Boolean} closure
*/
function Class(node, file, scope, isStatement) {
this.isStatement = isStatement;
this.scope = scope;
this.node = node;
this.file = file;
this.hasInstanceMutators = false;
this.hasStaticMutators = false;
this.instanceMutatorMap = {};
this.staticMutatorMap = {};
this.hasConstructor = false;
this.className = node.id || scope.generateUidIdentifier("class");
this.superName = node.superClass;
this.isLoose = file.isLoose("es6.classes");
}
/**
* Description
*
* @returns {Array}
*/
Class.prototype.run = function () {
var superName = this.superName;
var className = this.className;
var file = this.file;
//
var body = this.body = [];
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;
var closureParams = [];
var closureArgs = [];
//
if (superName) {
closureArgs.push(superName);
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])));
}
this.buildBody();
t.inheritsComments(body[0], this.node);
var init;
if (body.length === 1) {
// only a constructor so no need for a closure container
init = t.toExpression(constructor);
} else {
body.push(t.returnStatement(className));
init = t.callExpression(
t.functionExpression(null, closureParams, t.blockStatement(body)),
closureArgs
);
}
if (this.isStatement) {
return t.variableDeclaration("let", [
t.variableDeclarator(className, init)
]);
} else {
return init;
}
};
/**
* Description
*/
Class.prototype.buildBody = function () {
var constructor = this.constructor;
var className = this.className;
var superName = this.superName;
var classBody = this.node.body.body;
var body = this.body;
for (var i = 0; i < classBody.length; i++) {
var node = classBody[i];
if (t.isMethodDefinition(node)) {
var replaceSupers = new ReplaceSupers({
methodNode: node,
className: this.className,
superName: this.superName,
isLoose: this.isLoose,
scope: this.scope,
file: this.file
});
replaceSupers.replace();
if (node.key.name === "constructor") {
this.pushConstructor(node);
} else {
this.pushMethod(node);
}
} else if (t.isPrivateDeclaration(node)) {
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)) {
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));
}
var instanceProps;
var staticProps;
if (this.hasInstanceMutators) {
instanceProps = util.buildDefineProperties(this.instanceMutatorMap);
}
if (this.hasStaticMutators) {
staticProps = util.buildDefineProperties(this.staticMutatorMap);
}
if (instanceProps || staticProps) {
staticProps = staticProps || t.literal(null);
var args = [className, staticProps];
if (instanceProps) args.push(instanceProps);
body.push(t.expressionStatement(
t.callExpression(this.file.addHelper("prototype-properties"), args)
));
}
};
/**
* Push a method to it's respective mutatorMap.
*
* @param {Node} node MethodDefinition
*/
Class.prototype.pushMethod = function (node) {
var methodName = node.key;
var kind = node.kind;
if (kind === "") {
nameMethod.property(node, this.file, this.scope);
if (this.isLoose) {
// use assignments instead of define properties for loose classes
var className = this.className;
if (!node.static) className = t.memberExpression(className, t.identifier("prototype"));
methodName = t.memberExpression(className, methodName, node.computed);
var expr = t.expressionStatement(t.assignmentExpression("=", methodName, node.value));
t.inheritsComments(expr, node);
this.body.push(expr);
return;
}
kind = "value";
}
var mutatorMap = this.instanceMutatorMap;
if (node.static) {
this.hasStaticMutators = true;
mutatorMap = this.staticMutatorMap;
} else {
this.hasInstanceMutators = true;
}
util.pushMutatorMap(mutatorMap, methodName, kind, node.computed, node);
};
/**
* Replace the constructor body of our class.
*
* @param {Node} method MethodDefinition
*/
Class.prototype.pushConstructor = function (method) {
if (method.kind) {
throw this.file.errorWithNode(method, "illegal kind for constructor method");
}
var construct = this.constructor;
var fn = method.value;
this.hasConstructor = true;
t.inherits(construct, fn);
t.inheritsComments(construct, method);
construct._ignoreUserWhitespace = true;
construct.params = fn.params;
construct.body = fn.body;
};

View File

@@ -0,0 +1,41 @@
"use strict";
var traverse = require("../../../traverse");
var t = require("../../../types");
var visitor = {
enter: function (node, parent, scope, context, state) {
if (t.isDeclaration(node) || t.isAssignmentExpression(node)) {
var ids = t.getIds(node, true);
for (var key in ids) {
var id = ids[key];
var constant = state.constants[key];
// no constant exists
if (!constant) continue;
// check if the assignment id matches the constant declaration id
// if it does then it was the id used to initially declare the
// constant so we can just ignore it
if (id === constant) continue;
throw state.file.errorWithNode(id, key + " is read-only");
}
} else if (t.isScope(node)) {
context.skip();
}
}
};
exports.Scope = function (node, parent, scope, context, file) {
traverse(node, visitor, scope, {
constants: scope.getAllOfKind("const"),
file: file
});
};
exports.VariableDeclaration = function (node) {
if (node.kind === "const") node.kind = "let";
};

View File

@@ -1,18 +1,34 @@
"use strict";
// TODO: Clean up
var t = require("../../types");
var t = require("../../../types");
var buildVariableAssign = function (opts, id, init) {
var op = opts.operator;
if (t.isMemberExpression(id)) op = "=";
var node;
if (op) {
return t.expressionStatement(t.assignmentExpression("=", id, init));
node = t.expressionStatement(t.assignmentExpression(op, id, init));
} else {
return t.variableDeclaration(opts.kind, [
node = t.variableDeclaration(opts.kind, [
t.variableDeclarator(id, init)
]);
}
node._blockHoist = opts.blockHoist;
return node;
};
var buildVariableDeclar = function (opts, id, init) {
var declar = t.variableDeclaration("var", [
t.variableDeclarator(id, init)
]);
declar._blockHoist = opts.blockHoist;
return declar;
};
var push = function (opts, nodes, elem, parentId) {
@@ -46,27 +62,27 @@ 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) {
var prop2 = pattern.properties[i2];
// get all the keys that appear in this object before the current spread
var keys = [];
for (var i2 = 0; i2 < pattern.properties.length; i2++) {
var prop2 = pattern.properties[i2];
if (i2 >= i) break;
if (t.isSpreadProperty(prop2)) continue;
if (i2 >= i) break;
if (t.isSpreadProperty(prop2)) continue;
var key = prop2.key;
if (t.isIdentifier(key)) {
key = t.literal(prop2.key.name);
}
keys.push(key);
var key = prop2.key;
if (t.isIdentifier(key)) {
key = t.literal(prop2.key.name);
}
keys = t.arrayExpression(keys);
keys.push(key);
}
keys = t.arrayExpression(keys);
var value = t.callExpression(opts.file.addHelper("object-without-properties"), [parentId, keys]);
nodes.push(buildVariableAssign(opts, prop.argument, value));
var value = t.callExpression(opts.file.addHelper("object-without-properties"), [parentId, keys]);
nodes.push(buildVariableAssign(opts, prop.argument, value));
} else {
if (t.isLiteral(prop.key)) prop.computed = true;
@@ -87,23 +103,21 @@ var pushArrayPattern = function (opts, nodes, pattern, parentId) {
var i;
var hasSpreadElement = false;
for (i in pattern.elements) {
if (t.isSpreadElement(pattern.elements[i])) {
hasSpreadElement = true;
var hasRest = false;
for (i = 0; i < pattern.elements.length; i++) {
if (t.isRestElement(pattern.elements[i])) {
hasRest = true;
break;
}
}
var toArray = opts.file.toArray(parentId, !hasSpreadElement && pattern.elements.length);
var toArray = opts.file.toArray(parentId, !hasRest && pattern.elements.length);
var _parentId = opts.scope.generateUidBasedOnNode(parentId, opts.file);
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(_parentId, toArray)
]));
nodes.push(buildVariableDeclar(opts, _parentId, toArray));
parentId = _parentId;
for (i in pattern.elements) {
for (i = 0; i < pattern.elements.length; i++) {
var elem = pattern.elements[i];
if (!elem) continue;
@@ -111,7 +125,7 @@ var pushArrayPattern = function (opts, nodes, pattern, parentId) {
var newPatternId;
if (t.isSpreadElement(elem)) {
if (t.isRestElement(elem)) {
newPatternId = opts.file.toArray(parentId);
if (i > 0) {
@@ -131,16 +145,11 @@ var pushPattern = function (opts) {
var nodes = opts.nodes;
var pattern = opts.pattern;
var parentId = opts.id;
var file = opts.file;
var scope = opts.scope;
if (!t.isArrayExpression(parentId) && !t.isMemberExpression(parentId) && !t.isIdentifier(parentId)) {
var key = scope.generateUidBasedOnNode(parentId, file);
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(key, parentId)
]));
var key = scope.generateUidBasedOnNode(parentId);
nodes.push(buildVariableDeclar(opts, key, parentId));
parentId = key;
}
@@ -148,14 +157,14 @@ var pushPattern = function (opts) {
};
exports.ForInStatement =
exports.ForOfStatement = function (node, parent, file, scope) {
exports.ForOfStatement = function (node, parent, scope, context, file) {
var declar = node.left;
if (!t.isVariableDeclaration(declar)) return;
var pattern = declar.declarations[0].id;
if (!t.isPattern(pattern)) return;
var key = file.generateUidIdentifier("ref", scope);
var key = scope.generateUidIdentifier("ref");
node.left = t.variableDeclaration(declar.kind, [
t.variableDeclarator(key, null)
]);
@@ -174,24 +183,25 @@ exports.ForOfStatement = function (node, parent, file, scope) {
block.body = nodes.concat(block.body);
};
exports.Function = function (node, parent, file, scope) {
exports.Function = function (node, parent, scope, context, file) {
var nodes = [];
var hasDestructuring = false;
node.params = node.params.map(function (pattern) {
node.params = node.params.map(function (pattern, i) {
if (!t.isPattern(pattern)) return pattern;
hasDestructuring = true;
var parentId = file.generateUidIdentifier("ref", scope);
var parentId = scope.generateUidIdentifier("ref");
pushPattern({
kind: "var",
nodes: nodes,
pattern: pattern,
id: parentId,
file: file,
scope: scope
blockHoist: node.params.length - i,
pattern: pattern,
nodes: nodes,
scope: scope,
file: file,
kind: "var",
id: parentId
});
return parentId;
@@ -205,11 +215,11 @@ exports.Function = function (node, parent, file, scope) {
block.body = nodes.concat(block.body);
};
exports.CatchClause = function (node, parent, file, scope) {
exports.CatchClause = function (node, parent, scope, context, file) {
var pattern = node.param;
if (!t.isPattern(pattern)) return;
var ref = file.generateUidIdentifier("ref", scope);
var ref = scope.generateUidIdentifier("ref");
node.param = ref;
var nodes = [];
@@ -223,15 +233,15 @@ exports.CatchClause = function (node, parent, file, scope) {
node.body.body = nodes.concat(node.body.body);
};
exports.ExpressionStatement = function (node, parent, file, scope) {
exports.ExpressionStatement = function (node, parent, scope, context, file) {
var expr = node.expression;
if (expr.type !== "AssignmentExpression") return;
if (!t.isPattern(expr.left)) return;
if (file.isConsequenceExpressionStatement(node)) return;
var nodes = [];
var ref = file.generateUidIdentifier("ref", scope);
var ref = scope.generateUidIdentifier("ref");
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(ref, expr.right)
]));
@@ -245,14 +255,12 @@ exports.ExpressionStatement = function (node, parent, file, scope) {
return nodes;
};
exports.AssignmentExpression = function (node, parent, file, scope) {
if (parent.type === "ExpressionStatement") return;
exports.AssignmentExpression = function (node, parent, scope, context, file) {
if (!t.isPattern(node.left)) return;
var tempName = file.generateUid("temp", scope);
var ref = t.identifier(tempName);
var ref = scope.generateUidIdentifier("temp");
scope.push({
key: tempName,
key: ref.name,
id: ref
});
@@ -270,7 +278,7 @@ exports.AssignmentExpression = function (node, parent, file, scope) {
return t.toSequenceExpression(nodes, scope);
};
exports.VariableDeclaration = function (node, parent, file, scope) {
exports.VariableDeclaration = function (node, parent, scope, context, file) {
if (t.isForInStatement(parent) || t.isForOfStatement(parent)) return;
var nodes = [];
@@ -278,7 +286,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,18 +295,18 @@ 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;
var pattern = declar.id;
var opts = {
kind: node.kind,
nodes: nodes,
pattern: pattern,
id: patternId,
nodes: nodes,
scope: scope,
kind: node.kind,
file: file,
scope: scope
id: patternId,
};
if (t.isPattern(pattern) && patternId) {
@@ -317,7 +325,7 @@ exports.VariableDeclaration = function (node, parent, file, scope) {
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

@@ -1,11 +1,13 @@
var util = require("../../util");
var t = require("../../types");
"use strict";
exports.ForOfStatement = function (node, parent, file, scope) {
var util = require("../../../util");
var t = require("../../../types");
exports.ForOfStatement = function (node, parent, scope, context, file) {
var callback = spec;
if (file.isLoose("forOf")) callback = loose;
if (file.isLoose("es6.forOf")) callback = loose;
var build = callback(node, parent, file, scope);
var build = callback(node, parent, scope, context, file);
var declar = build.declar;
var loop = build.loop;
var block = loop.body;
@@ -17,7 +19,7 @@ exports.ForOfStatement = function (node, parent, file, scope) {
t.ensureBlock(node);
// add the value declaration to the new loop body
if (declar){
if (declar) {
if (build.shouldUnshift) {
block.body.unshift(declar);
} else {
@@ -28,10 +30,13 @@ exports.ForOfStatement = function (node, parent, file, scope) {
// push the rest of the original loop body onto our new body
block.body = block.body.concat(node.body.body);
// todo: find out why this is necessary? #538
loop._scopeInfo = node._scopeInfo;
return loop;
};
var loose = function (node, parent, file, scope) {
var loose = function (node, parent, scope, context, file) {
var left = node.left;
var declar, id;
@@ -49,10 +54,10 @@ var loose = function (node, parent, file, scope) {
}
var loop = util.template("for-of-loose", {
LOOP_OBJECT: file.generateUidIdentifier("iterator", scope),
IS_ARRAY: file.generateUidIdentifier("isArray", scope),
LOOP_OBJECT: scope.generateUidIdentifier("iterator"),
IS_ARRAY: scope.generateUidIdentifier("isArray"),
OBJECT: node.right,
INDEX: file.generateUidIdentifier("i", scope),
INDEX: scope.generateUidIdentifier("i"),
ID: id
});
@@ -63,11 +68,11 @@ var loose = function (node, parent, file, scope) {
};
};
var spec = function (node, parent, file, scope) {
var spec = function (node, parent, scope, context, file) {
var left = node.left;
var declar;
var stepKey = file.generateUidIdentifier("step", scope);
var stepKey = scope.generateUidIdentifier("step");
var stepValue = t.memberExpression(stepKey, t.identifier("value"));
if (t.isIdentifier(left) || t.isPattern(left)) {
@@ -83,7 +88,7 @@ var spec = function (node, parent, file, scope) {
}
var loop = util.template("for-of", {
ITERATOR_KEY: file.generateUidIdentifier("iterator", scope),
ITERATOR_KEY: scope.generateUidIdentifier("iterator"),
STEP_KEY: stepKey,
OBJECT: node.right
});

View File

@@ -1,16 +1,12 @@
var t = require("../../types");
"use strict";
exports.ast = {
before: function (ast, file) {
ast.program.body = file.dynamicImports.concat(ast.program.body);
}
};
var t = require("../../../types");
exports.ImportDeclaration = function (node, parent, file) {
exports.ImportDeclaration = function (node, parent, scope, context, 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 {
@@ -18,16 +14,16 @@ exports.ImportDeclaration = function (node, parent, file) {
}
if (nodes.length === 1) {
// inherit `_blockHoist`
// this for `_blockHoist` in File.prototype.addImport
// inherit `_blockHoist` - this is for `_blockHoist` in File.prototype.addImport
nodes[0]._blockHoist = node._blockHoist;
}
return nodes;
};
exports.ExportDeclaration = function (node, parent, file) {
exports.ExportDeclaration = function (node, parent, scope, context, file) {
var nodes = [];
var i;
if (node.declaration) {
// make sure variable exports have an initialiser
@@ -38,11 +34,17 @@ exports.ExportDeclaration = function (node, parent, file) {
}
file.moduleFormatter.exportDeclaration(node, nodes, parent);
} else {
for (var i in node.specifiers) {
} else if (node.specifiers) {
for (i = 0; i < node.specifiers.length; i++) {
file.moduleFormatter.exportSpecifier(node.specifiers[i], node, nodes, parent);
}
}
if (node._blockHoist) {
for (i = 0; i < nodes.length; i++) {
nodes[i]._blockHoist = node._blockHoist;
}
}
return nodes;
};

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