Compare commits

..

161 Commits

Author SHA1 Message Date
Alex Lam S.L
bba7cd0a70 v3.12.3 2020-12-22 23:59:53 +08:00
Alex Lam S.L
e1b2026929 improve object function generation in ufuzz (#4434) 2020-12-21 15:32:50 +08:00
Alex Lam S.L
c319030373 fix corner case in reduce_vars (#4433)
fixes #4432
2020-12-21 14:03:18 +08:00
Alex Lam S.L
47b63ed1a0 fix corner case in collapse_vars (#4431)
fixes #4430
2020-12-20 22:54:27 +08:00
Alex Lam S.L
7aefe97083 parse destructuring under strict mode correctly (#4429) 2020-12-20 20:48:51 +08:00
Alex Lam S.L
89198e0ad4 improve destructuring generation in ufuzz (#4428) 2020-12-20 13:38:56 +08:00
Alex Lam S.L
caea6aac81 handle destructuring catch in --reduce-test (#4427) 2020-12-20 11:22:45 +08:00
Alex Lam S.L
f5224ca1f5 fix corner case with destructuring catch (#4426)
fixes #4425
2020-12-20 10:31:32 +08:00
Alex Lam S.L
b7c49b72b3 support async function within object literal (#4424) 2020-12-20 08:19:04 +08:00
Alex Lam S.L
8ce3c7d70f fix corner case in evaluate & reduce_vars (#4423)
fixes #4422
2020-12-20 05:47:15 +08:00
Alex Lam S.L
87cf715213 fix corner case with destructuring catch (#4421)
fixes #4420
2020-12-20 05:47:01 +08:00
Alex Lam S.L
2c9c72e06c suppress false positives in ufuzz (#4419) 2020-12-20 02:31:09 +08:00
Alex Lam S.L
882968c68c fix corner case in inline (#4418)
fixes #4417
2020-12-20 01:24:29 +08:00
Alex Lam S.L
acc2d7d845 fix corner case in objects (#4416)
fixes #4415
2020-12-20 00:14:57 +08:00
Alex Lam S.L
9a5aede941 fix corner case in reduce_vars & unused (#4414)
fixes #4413
2020-12-19 12:47:46 +08:00
Alex Lam S.L
e6dd471f8f support destructuring of catch variable (#4412) 2020-12-19 12:28:38 +08:00
Alex Lam S.L
0f55bd92f1 fix corner case in arguments (#4411)
fixes #4410
2020-12-19 04:53:53 +08:00
Alex Lam S.L
7d9dad0289 fix corner case with parentheses (#4409)
fixes #4408
2020-12-19 01:01:49 +08:00
Alex Lam S.L
44e494f16f fix corner case in merge_vars (#4407)
fixes #4406
2020-12-19 00:52:37 +08:00
Alex Lam S.L
2415a72e75 fix corner case in unused (#4405)
fixes #4404
2020-12-18 23:45:41 +08:00
Alex Lam S.L
9c0718b162 enhance arrows (#4403) 2020-12-18 14:55:20 +08:00
Alex Lam S.L
d2c50ace99 fix corner case in merge_vars (#4402)
fixes #4401
2020-12-18 12:20:43 +08:00
Alex Lam S.L
1b646d3bc4 fix corner case in arguments (#4400)
fixes #4399
2020-12-18 10:12:01 +08:00
Alex Lam S.L
82d2aa4acf fix corner case in arguments (#4398)
fixes #4397
2020-12-18 09:42:07 +08:00
Alex Lam S.L
c1256c399a fix corner case in arguments (#4396)
fixes #4395
2020-12-18 08:41:13 +08:00
Alex Lam S.L
2c637fea8a fix corner case in evaluate & reduce_vars (#4394)
fixes #4393
2020-12-18 07:16:04 +08:00
Alex Lam S.L
4fa54b075c enhance reduce_vars (#4392) 2020-12-18 06:18:47 +08:00
Alex Lam S.L
ab82be82b2 fix corner case in collapse_vars (#4391)
fixes #4390
2020-12-18 03:10:16 +08:00
Alex Lam S.L
02fdcfde01 fix corner case in inline (#4389)
fixes #4388
2020-12-18 00:55:19 +08:00
Alex Lam S.L
a96f087ac3 support arrow function (#4385) 2020-12-17 18:23:41 +08:00
Alex Lam S.L
75e9fd8417 fix corner case in arguments (#4387)
fixes #4386
2020-12-17 13:51:34 +08:00
Alex Lam S.L
f68e267830 fix corner case in reduce_vars (#4384)
fixes #4383
2020-12-17 04:47:48 +08:00
Alex Lam S.L
8b10b93ee1 v3.12.2 2020-12-16 14:11:48 +08:00
Alex Lam S.L
549de028b6 fix corner case in objects (#4381)
fixes #4380
2020-12-15 21:23:55 +08:00
Alex Lam S.L
f579f1aa47 emulate global context in Node.js & web (#4379) 2020-12-14 02:05:07 +08:00
Alex Lam S.L
fcc40d0502 fix corner case in dead_code (#4378)
fixes #4377
2020-12-14 00:03:44 +08:00
Alex Lam S.L
b309527264 maintain compatibility options when testing (#4376) 2020-12-13 14:26:45 +08:00
Alex Lam S.L
5d19bb8d5d fix corner case in booleans (#4375)
fixes #4374
2020-12-13 05:01:38 +08:00
Alex Lam S.L
af97629912 fix corner case in dead_code (#4373)
fixes #4372
2020-12-13 02:24:18 +08:00
Alex Lam S.L
8c000033d3 clarify corner case in object literal (#4371)
closes #4366
2020-12-12 07:42:29 +08:00
Alex Lam S.L
fd0d28e465 fix corner case in spread (#4370) 2020-12-12 06:45:59 +08:00
Alex Lam S.L
2123f38394 fix asynchronous state tracking in ufuzz (#4369) 2020-12-12 05:19:56 +08:00
Alex Lam S.L
58dff9ada3 fix corner cases in unused & varify (#4368)
fixes #4365
2020-12-12 04:45:35 +08:00
Alex Lam S.L
4fdec765bc gate language features in ufuzz automatically (#4367) 2020-12-12 03:43:12 +08:00
Alex Lam S.L
1020d37256 fix corner case in spread (#4364)
fixes #4363
2020-12-12 02:19:11 +08:00
Alex Lam S.L
076739db07 fix corner case in unused (#4362)
fixes #4361
2020-12-12 00:57:05 +08:00
Alex Lam S.L
515e93d88a fix corner case in collapse_vars (#4360)
fixes #4359
2020-12-12 00:07:28 +08:00
Alex Lam S.L
57105b299e fix corner cases with spread syntax (#4358) 2020-12-11 06:59:21 +08:00
Alex Lam S.L
77e1bda426 improve fix for #4355 (#4357) 2020-12-11 00:48:41 +08:00
Alex Lam S.L
a59593cac8 fix corner case in loops & unused (#4356)
fixes #4355
2020-12-10 15:45:39 +08:00
Alex Lam S.L
046bbde9d4 fix corner case in keep_fargs & reduce_vars (#4354)
fixes #4353
2020-12-09 01:41:10 +08:00
Alex Lam S.L
fea9da9866 forbid AST_Await in computed function arguments (#4352)
fixes #4351
2020-12-08 12:59:08 +08:00
Alex Lam S.L
4733159782 fix corner cases with await (#4350)
fixes #4349
2020-12-08 11:26:03 +08:00
Alex Lam S.L
5fba98608c fix corner case in reduce_vars (#4348)
fixes #4347
2020-12-08 08:52:14 +08:00
Alex Lam S.L
c587d7917d introduce spread (#4346)
fixes #4345
2020-12-08 06:51:20 +08:00
Alex Lam S.L
336336f53f fix corner case with parentheses around await (#4344) 2020-12-08 04:29:54 +08:00
Alex Lam S.L
4bde50ce85 fix corner case in side_effects (#4343)
fixes #4342
2020-12-07 17:25:04 +08:00
Alex Lam S.L
fbecedf94c fix corner case in evaluate (#4341)
fixes #4340
2020-12-07 16:05:11 +08:00
Alex Lam S.L
2f31f95095 improve ufuzz (#4339) 2020-12-07 16:04:51 +08:00
Alex Lam S.L
6b603e1a62 fix corner case in unused (#4338)
fixes #4337
2020-12-07 13:23:53 +08:00
Alex Lam S.L
499f8d89ff fix corner case in inline (#4336)
fixes #4335
2020-12-07 11:30:37 +08:00
Alex Lam S.L
9eb65f3af3 extend trailing comma support (#4334) 2020-12-07 10:07:34 +08:00
Alex Lam S.L
2cbbf5c375 support async function (#4333) 2020-12-07 05:22:40 +08:00
Alex Lam S.L
3c384cf9a8 fix corner case in collapse_vars (#4332)
fixes #4331
2020-12-06 18:30:50 +08:00
Alex Lam S.L
37f4f56752 fix corner case in properties (#4330)
fixes #4329
2020-12-06 13:59:04 +08:00
Alex Lam S.L
1e4985ed9e support spread syntax (#4328) 2020-12-06 05:19:31 +08:00
Alex Lam S.L
d2d56e301e v3.12.1 2020-12-01 01:46:27 +08:00
Alex Lam S.L
9d34f8428b fix corner case in side_effects (#4326)
fixes #4325
2020-11-29 10:05:48 +08:00
Alex Lam S.L
f045e2b460 fix corner case in merge_vars (#4324)
fixes #4323
2020-11-29 05:38:24 +08:00
Alex Lam S.L
8791f258e3 fix corner case in inline (#4322)
fixes #4321
2020-11-29 03:48:42 +08:00
Alex Lam S.L
af1cca25bf fix corner case in inline (#4320)
fixes #4319
2020-11-27 01:31:06 +08:00
Alex Lam S.L
9b3a363604 fix infinite recursion in ufuzz (#4318) 2020-11-25 09:33:42 +08:00
Alex Lam S.L
1e8fa1aa1d fix corner case in passes & reduce_vars (#4316)
fixes #4315
2020-11-23 07:05:20 +08:00
Alex Lam S.L
9f67866147 v3.12.0 2020-11-23 01:10:39 +08:00
Alex Lam S.L
645d5a348b workaround Safari quirks (#4314)
fixes #1753
2020-11-21 10:30:46 +08:00
Alex Lam S.L
cf120c7cea fix corner case in merge_vars & reduce_vars (#4313)
fixes #4312
2020-11-21 08:57:59 +08:00
Alex Lam S.L
8d30902ba9 fix corner case in mangle (#4311) 2020-11-21 08:05:40 +08:00
Alex Lam S.L
02459cddf9 gate galio workaround (#4310) 2020-11-21 03:37:33 +08:00
Alex Lam S.L
1b579779be fix corner case in collapse_vars (#4309)
fixes #4308
2020-11-20 06:23:37 +08:00
Alex Lam S.L
b18b70f63b fix corner case in hoist_props (#4307) 2020-11-20 00:02:25 +08:00
Alex Lam S.L
641406d491 fix corner cases in reduce_vars & unused (#4306) 2020-11-19 11:25:36 +08:00
Alex Lam S.L
134ef0b1eb fix corner case in dead_code (#4304) 2020-11-19 08:34:55 +08:00
Alex Lam S.L
db87dcf13e enhance varify (#4303) 2020-11-19 07:58:33 +08:00
Alex Lam S.L
aecbabc587 fix corner case in merge_vars (#4302)
fixes #4301
2020-11-19 05:44:47 +08:00
Alex Lam S.L
fd6544b340 fix corner case reduce_vars (#4300)
fixes #4297
2020-11-19 01:11:28 +08:00
Alex Lam S.L
f6a83f7944 fix corner case in merge_vars (#4299)
fixes #4298
2020-11-18 23:43:55 +08:00
Alex Lam S.L
35283e5dd1 enhance arguments (#4296) 2020-11-18 11:39:32 +08:00
Alex Lam S.L
7a51c17ff0 fix corner case in merge_vars (#4295)
fixes #4294
2020-11-18 09:32:53 +08:00
Alex Lam S.L
aff842f2f9 fix corner case in arguments (#4293)
fixes #4291
2020-11-18 08:54:58 +08:00
Alex Lam S.L
0bedd031da fix corner cases in collapse_vars, unused & varify (#4292)
fixes #4290
2020-11-18 08:22:54 +08:00
Alex Lam S.L
caa92aea5d fix corner case in merge_vars (#4289)
fixes #4288
2020-11-18 04:03:20 +08:00
Alex Lam S.L
383163afa6 fix corner case in collapse_vars (#4287)
fixes #4286
2020-11-17 18:03:31 +08:00
Alex Lam S.L
8a83c8dd46 fix corner cases in collapse_vars & dead_code (#4285)
fixes #4284
2020-11-17 16:23:50 +08:00
Alex Lam S.L
2a612fd472 fix corner case in reduce_vars (#4283)
fixes #4282
2020-11-17 14:43:04 +08:00
Alex Lam S.L
b9798a01a8 fix corner case in reduce_vars (#4281)
fixes #4280
2020-11-17 12:59:44 +08:00
Alex Lam S.L
6dbacb5e3f enhance varify (#4279) 2020-11-17 12:35:00 +08:00
Alex Lam S.L
e5f80afc53 support destructured literals (#4278) 2020-11-17 08:01:24 +08:00
Alex Lam S.L
42e34c870a fix corner case in unused (#4277)
fixes #4276
2020-11-17 02:06:00 +08:00
Alex Lam S.L
e390e7e124 v3.11.6 2020-11-14 22:21:19 +08:00
Alex Lam S.L
6fd5b5b371 fix corner case in loops (#4275)
fixes #4274
2020-11-14 02:08:05 +08:00
Alex Lam S.L
fba27bfb71 fix corner case in evaluate (#4272)
fixes #4271
2020-11-11 00:06:13 +08:00
Alex Lam S.L
41310e6404 fix corner case in objects (#4270)
fixes #4269
2020-11-09 10:47:02 +08:00
Alex Lam S.L
91fc1c82b5 support computed property name in object literal (#4268) 2020-11-08 23:38:32 +08:00
Alex Lam S.L
810cd40356 fix corner case in inline (#4266)
fixes #4265
2020-11-08 18:50:08 +08:00
Alex Lam S.L
1cbd07e789 support shorthand method name in object literal (#4264) 2020-11-08 13:17:53 +08:00
Alex Lam S.L
b82de04775 support shorthand property name in object literal (#4263) 2020-11-08 10:44:44 +08:00
Alex Lam S.L
4bbeb09f7c fix corner case in reduce_vars (#4262)
fixes #4261
2020-11-07 10:00:04 +08:00
Alex Lam S.L
c2f6fd5fde fix corner case in functions (#4260)
fixes #4259
2020-11-06 03:55:25 +08:00
Alex Lam S.L
af4ea3ff69 v3.11.5 2020-11-03 08:59:02 +08:00
Alex Lam S.L
e7643248a3 fix corner case in merge_vars (#4258)
fixes #4257
2020-11-02 01:01:00 +08:00
Alex Lam S.L
68091dbf69 fix corner case in merge_vars (#4256)
fixes #4255
2020-11-01 14:34:07 +08:00
Alex Lam S.L
cbf7269296 fix corner case in merge_vars (#4254)
fixes #4253
2020-11-01 10:37:21 +08:00
Alex Lam S.L
d8563caba7 improve resilience against spurious time-outs (#4252) 2020-10-30 11:06:48 +08:00
Alex Lam S.L
2e0ad40fe6 fix corner case in ie8 (#4251)
fixes #4250
2020-10-30 11:06:31 +08:00
Alex Lam S.L
5d12abc41b fix corner cases in collapse_vars (#4249)
fixes #4248
2020-10-30 10:04:23 +08:00
Alex Lam S.L
79e5c3f564 improve warnings (#4247)
closes #4244
2020-10-27 17:39:33 +08:00
Alex Lam S.L
607f87c5cd fix corner case in booleans (#4246)
fixes #4245
2020-10-26 18:53:58 +08:00
Alex Lam S.L
b2775746a7 v3.11.4 2020-10-25 23:40:42 +00:00
Alex Lam S.L
e478da24c7 fix corner case in collapse_vars (#4243)
fixes #4242
2020-10-24 22:44:20 +08:00
Alex Lam S.L
c5df8355ba fix corner case in loops & unused (#4241)
fixes #4240
2020-10-24 13:33:48 +08:00
Alex Lam S.L
ff38d2471f improve resilience against npm failures (#4239) 2020-10-24 11:22:13 +08:00
Alex Lam S.L
8e86d05c32 fix corner case in merge_vars (#4238)
fixes #4237
2020-10-24 10:19:43 +08:00
Alex Lam S.L
9e40abeded fix corner case in unused (#4236)
fixes #4235
2020-10-22 22:19:47 +08:00
Alex Lam S.L
23ca7d675f fix corner case in functions (#4234)
fixes #4233
2020-10-22 10:13:11 +08:00
Alex Lam S.L
fd8c0212b8 fix corner case in ie8 (#4232)
fixes #4231
2020-10-20 14:02:39 +08:00
Alex Lam S.L
256950c2c0 fix corner case in ie8 (#4230)
fixes #4229
2020-10-20 06:13:23 +08:00
Alex Lam S.L
8ecaa40c6e extend support for Unicode (#4228) 2020-10-19 09:34:17 +08:00
Alex Lam S.L
96bf7fceab support let (#4227) 2020-10-19 08:32:39 +08:00
Alex Lam S.L
6c7226c10e v3.11.3 2020-10-19 07:25:47 +08:00
Alex Lam S.L
dc575919e2 fix corner case in side_effects (#4226)
fixes #4225
2020-10-18 22:13:10 +08:00
Alex Lam S.L
4298201938 flush stdout from ufuzz jobs properly (#4224) 2020-10-16 21:56:54 +08:00
Alex Lam S.L
4f833937fe fix corner case in inline (#4223)
fixes #4222
2020-10-15 21:52:40 +08:00
Alex Lam S.L
3d71e97dd1 fix corner cases in braces & sequences (#4221)
fixes #4220
2020-10-14 23:39:35 +08:00
Alex Lam S.L
7f35d9cee0 fix corner case in reduce_vars (#4219)
fixes #4218
2020-10-14 07:58:04 +08:00
Alex Lam S.L
9f8106e1d8 fix corner case in collapse_vars (#4217)
fixes #4216
2020-10-14 07:18:26 +08:00
Alex Lam S.L
b7b8435721 fix corner case in evaluate (#4215)
fixes #4214
2020-10-14 02:49:45 +08:00
Alex Lam S.L
c0c04c33bb fix corner cases in dead_code & reduce_vars (#4213)
fixes #4212
2020-10-14 00:09:17 +08:00
Alex Lam S.L
0e234a25c5 fix corner case in reduce_vars (#4211)
fixes #4210
2020-10-13 15:52:03 +08:00
Alex Lam S.L
3096f6fdad restore inline functionality disabled by #4204 (#4209) 2020-10-13 09:33:49 +08:00
Alex Lam S.L
176c09c6a5 fix corner case in reduce_vars & unused (#4208)
fixes #4207
2020-10-13 07:32:17 +08:00
Alex Lam S.L
9272f662c0 fix corner case in collapse_vars (#4206)
fixes #4205
2020-10-13 01:30:21 +08:00
Alex Lam S.L
4d33cb2f94 fix corner case in inilne (#4204)
fixes #4202
2020-10-12 23:10:32 +08:00
Alex Lam S.L
00d0eda85b fix corner case in arguments (#4201)
fixes #4200
2020-10-12 19:03:21 +08:00
Alex Lam S.L
1cdf810f0b fix corner case in reduce_vars (#4203)
fixes #4198
2020-10-12 19:02:44 +08:00
Alex Lam S.L
b512726cf3 fix corner case in collapse_vars (#4199)
fixes #4197
2020-10-12 14:13:17 +08:00
Alex Lam S.L
9b7a13c8c7 fix corner case in ie8 & mangle (#4196)
fixes #4195
2020-10-12 12:43:26 +08:00
Alex Lam S.L
74ff6ce261 fix corner case in dead_code (#4194)
fixes #4193
2020-10-12 11:09:26 +08:00
Alex Lam S.L
b1b8898e7c fix corner case in functions (#4192)
fixes #4191
2020-10-12 09:26:56 +08:00
Alex Lam S.L
55451e7b78 support const (#4190) 2020-10-12 01:18:57 +08:00
Alex Lam S.L
ffcce28ce1 v3.11.2 2020-10-11 21:19:25 +08:00
Alex Lam S.L
9c0feb69e5 fix corner case in reduce_vars (#4189)
fixes #4188
2020-10-07 22:01:39 +08:00
Alex Lam S.L
bc6e105174 fix corner case in ie8 (#4187)
fixes #4186
2020-10-06 09:20:41 +08:00
Alex Lam S.L
b91a2459c0 fix corner case in unused (#4185)
fixes #4184
2020-10-05 18:59:03 +08:00
Alex Lam S.L
b7a57fc69d fix corner case in loops (#4183)
fixes #4182
2020-10-05 17:28:46 +08:00
Alex Lam S.L
2dbe40b01b enhance conditionals (#4181) 2020-10-05 15:55:37 +08:00
Alex Lam S.L
813ac3ba96 enhance loops (#4180) 2020-10-05 08:26:59 +08:00
Alex Lam S.L
220dc95c0d clean up scope-related variables (#4179) 2020-10-05 06:56:52 +08:00
Alex Lam S.L
8f0521d51d retrofit try-catch-finally as block-scoped (#4178)
- support optional catch binding
2020-10-05 05:30:14 +08:00
Alex Lam S.L
f9946767c9 retrofit AST_BlockStatement as block-scoped (#4177) 2020-10-05 01:58:50 +08:00
Alex Lam S.L
58ac5b9bd5 extend support for numeral literals (#4176) 2020-10-05 00:05:03 +08:00
Alex Lam S.L
66140b459e enhance side_effects (#4175) 2020-10-04 23:43:49 +08:00
62 changed files with 13343 additions and 1680 deletions

View File

@@ -4,10 +4,12 @@ UglifyJS 3
UglifyJS is a JavaScript parser, minifier, compressor and beautifier toolkit. UglifyJS is a JavaScript parser, minifier, compressor and beautifier toolkit.
#### Note: #### Note:
- **`uglify-js@3` has a simplified [API](#api-reference) and [CLI](#command-line-usage) that is not backwards compatible with [`uglify-js@2`](https://github.com/mishoo/UglifyJS/tree/v2.x)**. - **`uglify-js@3` has a simplified [API](#api-reference) and [CLI](#command-line-usage)
that is not backwards compatible with [`uglify-js@2`](https://github.com/mishoo/UglifyJS/tree/v2.x)**.
- **Documentation for UglifyJS `2.x` releases can be found [here](https://github.com/mishoo/UglifyJS/tree/v2.x)**. - **Documentation for UglifyJS `2.x` releases can be found [here](https://github.com/mishoo/UglifyJS/tree/v2.x)**.
- `uglify-js` only supports JavaScript (ECMAScript 5). - `uglify-js` supports ECMAScript 5 and some newer language features.
- To minify ECMAScript 2015 or above, transpile using tools like [Babel](https://babeljs.io/). - To minify ECMAScript 2015 or above, you may need to transpile using tools like
[Babel](https://babeljs.io/).
Install Install
------- -------
@@ -135,6 +137,10 @@ a double dash to prevent input files being used as option arguments:
--toplevel Compress and/or mangle variables in top level scope. --toplevel Compress and/or mangle variables in top level scope.
--verbose Print diagnostic messages. --verbose Print diagnostic messages.
--warn Print warning messages. --warn Print warning messages.
--webkit Support non-standard Safari/Webkit.
Equivalent to setting `webkit: true` in `minify()`
for `mangle` and `output` options.
By default UglifyJS will not try to be Safari-proof.
--wrap <name> Embed everything in a big function, making the --wrap <name> Embed everything in a big function, making the
“exports” and “global” variables available. You “exports” and “global” variables available. You
need to pass an argument to this option to need to pass an argument to this option to
@@ -519,6 +525,9 @@ if (result.error) throw result.error;
- `warnings` (default `false`) — pass `true` to return compressor warnings - `warnings` (default `false`) — pass `true` to return compressor warnings
in `result.warnings`. Use the value `"verbose"` for more detailed warnings. in `result.warnings`. Use the value `"verbose"` for more detailed warnings.
- `webkit` (default `false`) -- enable workarounds for Safari/WebKit bugs.
PhantomJS users should set this option to `true`.
## Minify options structure ## Minify options structure
```javascript ```javascript
@@ -744,6 +753,8 @@ to be `false` and all symbol names will be omitted.
annotation `/*@__PURE__*/` or `/*#__PURE__*/` immediately precedes the call. For annotation `/*@__PURE__*/` or `/*#__PURE__*/` immediately precedes the call. For
example: `/*@__PURE__*/foo();` example: `/*@__PURE__*/foo();`
- `spread` (default: `true`) -- flatten spread expressions.
- `strings` (default: `true`) -- compact string concatenations. - `strings` (default: `true`) -- compact string concatenations.
- `switches` (default: `true`) -- de-duplicate and remove unreachable `switch` branches - `switches` (default: `true`) -- de-duplicate and remove unreachable `switch` branches
@@ -784,6 +795,9 @@ to be `false` and all symbol names will be omitted.
- `unused` (default: `true`) -- drop unreferenced functions and variables (simple - `unused` (default: `true`) -- drop unreferenced functions and variables (simple
direct variable assignments do not count as references unless set to `"keep_assign"`) direct variable assignments do not count as references unless set to `"keep_assign"`)
- `varify` (default: `true`) -- convert block-scoped declaractions into `var`
whenever safe to do so
## Mangle options ## Mangle options
- `eval` (default `false`) -- Pass `true` to mangle names visible in scopes - `eval` (default `false`) -- Pass `true` to mangle names visible in scopes
@@ -865,6 +879,8 @@ can pass additional arguments that control the code output:
} }
``` ```
- `galio` (default `false`) -- enable workarounds for ANT Galio bugs
- `indent_level` (default `4`) - `indent_level` (default `4`)
- `indent_start` (default `0`) -- prefix all lines by that many spaces - `indent_start` (default `0`) -- prefix all lines by that many spaces
@@ -903,8 +919,7 @@ can pass additional arguments that control the code output:
- `shebang` (default `true`) -- preserve shebang `#!` in preamble (bash scripts) - `shebang` (default `true`) -- preserve shebang `#!` in preamble (bash scripts)
- `webkit` (default `false`) -- enable workarounds for WebKit bugs. - `v8` (default `false`) -- enable workarounds for Chrome & Node.js bugs
PhantomJS users should set this option to `true`.
- `width` (default `80`) -- only takes effect when beautification is on, this - `width` (default `80`) -- only takes effect when beautification is on, this
specifies an (orientative) line width that the beautifier will try to specifies an (orientative) line width that the beautifier will try to
@@ -1135,7 +1150,7 @@ To enable fast minify mode with the API use:
UglifyJS.minify(code, { compress: false, mangle: true }); UglifyJS.minify(code, { compress: false, mangle: true });
``` ```
#### Source maps and debugging ### Source maps and debugging
Various `compress` transforms that simplify, rearrange, inline and remove code Various `compress` transforms that simplify, rearrange, inline and remove code
are known to have an adverse effect on debugging with source maps. This is are known to have an adverse effect on debugging with source maps. This is
@@ -1147,6 +1162,10 @@ disable the Uglify `compress` option and just use `mangle`.
To allow for better optimizations, the compiler makes various assumptions: To allow for better optimizations, the compiler makes various assumptions:
- The code does not rely on preserving its runtime performance characteristics.
Typically uglified code will run faster due to less instructions and easier
inlining, but may be slower on rare occasions for a specific platform, e.g.
see [`reduce_funcs`](#compress-options).
- `.toString()` and `.valueOf()` don't have side effects, and for built-in - `.toString()` and `.valueOf()` don't have side effects, and for built-in
objects they have not been overridden. objects they have not been overridden.
- `undefined`, `NaN` and `Infinity` have not been externally redefined. - `undefined`, `NaN` and `Infinity` have not been externally redefined.
@@ -1158,6 +1177,18 @@ To allow for better optimizations, the compiler makes various assumptions:
- Object properties can be added, removed and modified (not prevented with - Object properties can be added, removed and modified (not prevented with
`Object.defineProperty()`, `Object.defineProperties()`, `Object.freeze()`, `Object.defineProperty()`, `Object.defineProperties()`, `Object.freeze()`,
`Object.preventExtensions()` or `Object.seal()`). `Object.preventExtensions()` or `Object.seal()`).
- Earlier versions of JavaScript will throw `SyntaxError` with the following:
```js
({
p: 42,
get p() {},
});
// SyntaxError: Object literal may not have data and accessor property with
// the same name
```
UglifyJS may modify the input which in turn may suppress those errors.
- Iteration order of keys over an object which contains spread syntax in later
versions of Chrome and Node.js may be altered.
- When `toplevel` is enabled, UglifyJS effectively assumes input code is wrapped - When `toplevel` is enabled, UglifyJS effectively assumes input code is wrapped
within `function(){ ... }`, thus forbids aliasing of declared global variables: within `function(){ ... }`, thus forbids aliasing of declared global variables:
```js ```js
@@ -1174,3 +1205,39 @@ To allow for better optimizations, the compiler makes various assumptions:
top.B = "PASS"; top.B = "PASS";
console.log(B); console.log(B);
``` ```
- Use of `arguments` alongside destructuring as function parameters, e.g.
`function({}, arguments) {}` will result in `SyntaxError` in earlier versions
of Chrome and Node.js - UglifyJS may modify the input which in turn may
suppress those errors.
- Earlier versions of Chrome and Node.js will throw `ReferenceError` with the
following:
```js
var a;
try {
throw 42;
} catch ({
[a]: b,
// ReferenceError: a is not defined
}) {
let a;
}
```
UglifyJS may modify the input which in turn may suppress those errors.
- Later versions of JavaScript will throw `SyntaxError` with the following:
```js
a => {
let a;
};
// SyntaxError: Identifier 'a' has already been declared
```
UglifyJS may modify the input which in turn may suppress those errors.
- Later versions of JavaScript will throw `SyntaxError` with the following:
```js
try {
// ...
} catch ({ message: a }) {
var a;
}
// SyntaxError: Identifier 'a' has already been declared
```
UglifyJS may modify the input which in turn may suppress those errors.

View File

@@ -111,6 +111,7 @@ function process_option(name, no_value) {
" --validate Perform validation during AST manipulations.", " --validate Perform validation during AST manipulations.",
" --verbose Print diagnostic messages.", " --verbose Print diagnostic messages.",
" --warn Print warning messages.", " --warn Print warning messages.",
" --webkit Support non-standard Safari/Webkit.",
" --wrap <name> Embed everything as a function with “exports” corresponding to “name” globally.", " --wrap <name> Embed everything as a function with “exports” corresponding to “name” globally.",
" --reduce-test Reduce a standalone test case (assumes cloned repository).", " --reduce-test Reduce a standalone test case (assumes cloned repository).",
].join("\n")); ].join("\n"));
@@ -142,6 +143,7 @@ function process_option(name, no_value) {
case "timings": case "timings":
case "toplevel": case "toplevel":
case "validate": case "validate":
case "webkit":
options[name] = true; options[name] = true;
break; break;
case "keep-fnames": case "keep-fnames":
@@ -276,7 +278,9 @@ function convert_ast(fn) {
function run() { function run() {
var content = options.sourceMap && options.sourceMap.content; var content = options.sourceMap && options.sourceMap.content;
if (content && content != "inline") { if (content && content != "inline") {
UglifyJS.AST_Node.info("Using input source map: " + content); UglifyJS.AST_Node.info("Using input source map: {content}", {
content : content,
});
options.sourceMap.content = read_file(content, content); options.sourceMap.content = read_file(content, content);
} }
try { try {

View File

@@ -137,17 +137,17 @@ var AST_Node = DEFNODE("Node", "start end", {
}, null); }, null);
(AST_Node.log_function = function(fn, verbose) { (AST_Node.log_function = function(fn, verbose) {
var printed = Object.create(null); if (!fn) {
if (fn) {
AST_Node.info = verbose ? function(text, props) {
log("INFO: " + string_template(text, props));
} : noop;
AST_Node.warn = function(text, props) {
log("WARN: " + string_template(text, props));
};
} else {
AST_Node.info = AST_Node.warn = noop; AST_Node.info = AST_Node.warn = noop;
return;
} }
var printed = Object.create(null);
AST_Node.info = verbose ? function(text, props) {
log("INFO: " + string_template(text, props));
} : noop;
AST_Node.warn = function(text, props) {
log("WARN: " + string_template(text, props));
};
function log(msg) { function log(msg) {
if (printed[msg]) return; if (printed[msg]) return;
@@ -203,9 +203,15 @@ var AST_Directive = DEFNODE("Directive", "value quote", {
}, },
}, AST_Statement); }, AST_Statement);
var AST_EmptyStatement = DEFNODE("EmptyStatement", null, {
$documentation: "The empty statement (empty block or simply a semicolon)"
}, AST_Statement);
function must_be_expression(node, prop) { function must_be_expression(node, prop) {
if (!(node[prop] instanceof AST_Node)) throw new Error(prop + " must be AST_Node"); if (!(node[prop] instanceof AST_Node)) throw new Error(prop + " must be AST_Node");
if (node[prop] instanceof AST_Statement && !(node[prop] instanceof AST_Function)) { if (node[prop] instanceof AST_Hole) throw new Error(prop + " cannot be AST_Hole");
if (node[prop] instanceof AST_Spread) throw new Error(prop + " cannot be AST_Spread");
if (node[prop] instanceof AST_Statement && !is_function(node[prop])) {
throw new Error(prop + " cannot be AST_Statement"); throw new Error(prop + " cannot be AST_Statement");
} }
} }
@@ -226,6 +232,34 @@ var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", {
}, },
}, AST_Statement); }, AST_Statement);
var AST_BlockScope = DEFNODE("BlockScope", "enclosed functions make_def parent_scope variables", {
$documentation: "Base class for all statements introducing a lexical scope",
$propdoc: {
enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",
functions: "[Object/S] like `variables`, but only lists function declarations",
parent_scope: "[AST_Scope?/S] link to the parent scope",
variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope",
},
clone: function(deep) {
var node = this._clone(deep);
if (this.enclosed) node.enclosed = this.enclosed.slice();
if (this.functions) node.functions = this.functions.clone();
if (this.variables) node.variables = this.variables.clone();
return node;
},
pinned: function() {
return this.resolve().pinned();
},
resolve: function() {
return this.parent_scope.resolve();
},
_validate: function() {
if (this.parent_scope == null) return;
if (!(this.parent_scope instanceof AST_BlockScope)) throw new Error("parent_scope must be AST_BlockScope");
if (!(this.resolve() instanceof AST_Scope)) throw new Error("must be contained within AST_Scope");
},
}, AST_Statement);
function walk_body(node, visitor) { function walk_body(node, visitor) {
node.body.forEach(function(node) { node.body.forEach(function(node) {
node.walk(visitor); node.walk(visitor);
@@ -246,19 +280,15 @@ var AST_Block = DEFNODE("Block", "body", {
_validate: function() { _validate: function() {
this.body.forEach(function(node) { this.body.forEach(function(node) {
if (!(node instanceof AST_Statement)) throw new Error("body must be AST_Statement[]"); if (!(node instanceof AST_Statement)) throw new Error("body must be AST_Statement[]");
if (node instanceof AST_Function) throw new Error("body cannot contain AST_Function"); if (is_function(node)) throw new Error("body cannot contain AST_Function");
}); });
}, },
}, AST_Statement); }, AST_BlockScope);
var AST_BlockStatement = DEFNODE("BlockStatement", null, { var AST_BlockStatement = DEFNODE("BlockStatement", null, {
$documentation: "A block statement", $documentation: "A block statement",
}, AST_Block); }, AST_Block);
var AST_EmptyStatement = DEFNODE("EmptyStatement", null, {
$documentation: "The empty statement (empty block or simply a semicolon)"
}, AST_Statement);
var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", { var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", {
$documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`", $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`",
$propdoc: { $propdoc: {
@@ -266,9 +296,9 @@ var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", {
}, },
_validate: function() { _validate: function() {
if (!(this.body instanceof AST_Statement)) throw new Error("body must be AST_Statement"); if (!(this.body instanceof AST_Statement)) throw new Error("body must be AST_Statement");
if (this.body instanceof AST_Function) throw new Error("body cannot be AST_Function"); if (is_function(this.body)) throw new Error("body cannot be AST_Function");
}, },
}, AST_Statement); }, AST_BlockScope);
var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", { var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", {
$documentation: "Statement with a label", $documentation: "Statement with a label",
@@ -360,7 +390,7 @@ var AST_For = DEFNODE("For", "init condition step", {
if (this.init != null) { if (this.init != null) {
if (!(this.init instanceof AST_Node)) throw new Error("init must be AST_Node"); if (!(this.init instanceof AST_Node)) throw new Error("init must be AST_Node");
if (this.init instanceof AST_Statement if (this.init instanceof AST_Statement
&& !(this.init instanceof AST_Definitions || this.init instanceof AST_Function)) { && !(this.init instanceof AST_Definitions || is_function(this.init))) {
throw new Error("init cannot be AST_Statement"); throw new Error("init cannot be AST_Statement");
} }
} }
@@ -386,8 +416,12 @@ var AST_ForIn = DEFNODE("ForIn", "init object", {
_validate: function() { _validate: function() {
if (this.init instanceof AST_Definitions) { if (this.init instanceof AST_Definitions) {
if (this.init.definitions.length != 1) throw new Error("init must have single declaration"); if (this.init.definitions.length != 1) throw new Error("init must have single declaration");
} else if (!(this.init instanceof AST_PropAccess || this.init instanceof AST_SymbolRef)) { } else {
throw new Error("init must be assignable"); validate_destructured(this.init, function(node) {
if (!(node instanceof AST_PropAccess || node instanceof AST_SymbolRef)) {
throw new Error("init must be assignable: " + node.TYPE);
}
});
} }
must_be_expression(this, "object"); must_be_expression(this, "object");
}, },
@@ -412,38 +446,9 @@ var AST_With = DEFNODE("With", "expression", {
/* -----[ scope and functions ]----- */ /* -----[ scope and functions ]----- */
var AST_BlockScope = DEFNODE("BlockScope", "enclosed functions make_def parent_scope variables", { var AST_Scope = DEFNODE("Scope", "uses_eval uses_with", {
$documentation: "Base class for all statements introducing a lexical scope", $documentation: "Base class for all statements introducing a lexical scope",
$propdoc: { $propdoc: {
enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",
functions: "[Object/S] like `variables`, but only lists function declarations",
parent_scope: "[AST_Scope?/S] link to the parent scope",
variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope",
},
clone: function(deep) {
var node = this._clone(deep);
if (this.enclosed) node.enclosed = this.enclosed.slice();
if (this.functions) node.functions = this.functions.clone();
if (this.variables) node.variables = this.variables.clone();
return node;
},
pinned: function() {
return this.resolve().pinned();
},
resolve: function() {
return this.parent_scope.resolve();
},
_validate: function() {
if (this.parent_scope == null) return;
if (!(this.parent_scope instanceof AST_BlockScope)) throw new Error("parent_scope must be AST_BlockScope");
if (!(this.resolve() instanceof AST_Scope)) throw new Error("must be contained within AST_Scope");
},
}, AST_Block);
var AST_Scope = DEFNODE("Scope", "cname uses_eval uses_with", {
$documentation: "Base class for all statements introducing a lexical scope",
$propdoc: {
cname: "[integer/S] current index for mangling variables (used internally by the mangler)",
uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`", uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`",
uses_with: "[boolean/S] tells whether this scope uses the `with` statement", uses_with: "[boolean/S] tells whether this scope uses the `with` statement",
}, },
@@ -451,7 +456,7 @@ var AST_Scope = DEFNODE("Scope", "cname uses_eval uses_with", {
return this.uses_eval || this.uses_with; return this.uses_eval || this.uses_with;
}, },
resolve: return_this, resolve: return_this,
}, AST_BlockScope); }, AST_Block);
var AST_Toplevel = DEFNODE("Toplevel", "globals", { var AST_Toplevel = DEFNODE("Toplevel", "globals", {
$documentation: "The toplevel scope", $documentation: "The toplevel scope",
@@ -497,12 +502,23 @@ var AST_Toplevel = DEFNODE("Toplevel", "globals", {
} }
}, AST_Scope); }, AST_Scope);
var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments length_read", { var AST_Lambda = DEFNODE("Lambda", "argnames length_read uses_arguments", {
$documentation: "Base class for functions", $documentation: "Base class for functions",
$propdoc: { $propdoc: {
name: "[AST_SymbolDeclaration?] the name of this function", argnames: "[(AST_Destructured|AST_SymbolFunarg)*] array of function arguments and/or destructured literals",
argnames: "[AST_SymbolFunarg*] array of function arguments", uses_arguments: "[boolean/S] tells whether this function accesses the arguments array",
uses_arguments: "[boolean/S] tells whether this function accesses the arguments array" },
each_argname: function(visit) {
var tw = new TreeWalker(function(node) {
if (node instanceof AST_DestructuredKeyVal) {
node.value.walk(tw);
return true;
}
if (node instanceof AST_SymbolFunarg) visit(node);
});
this.argnames.forEach(function(argname) {
argname.walk(tw);
});
}, },
walk: function(visitor) { walk: function(visitor) {
var node = this; var node = this;
@@ -516,20 +532,61 @@ var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments length_read", {
}, },
_validate: function() { _validate: function() {
this.argnames.forEach(function(node) { this.argnames.forEach(function(node) {
if (!(node instanceof AST_SymbolFunarg)) throw new Error("argnames must be AST_SymbolFunarg[]"); validate_destructured(node, function(node) {
if (!(node instanceof AST_SymbolFunarg)) throw new Error("argnames must be AST_SymbolFunarg[]");
});
}); });
}, },
}, AST_Scope); }, AST_Scope);
var AST_Accessor = DEFNODE("Accessor", null, { var AST_Accessor = DEFNODE("Accessor", null, {
$documentation: "A setter/getter function. The `name` property is always null.", $documentation: "A getter/setter function",
_validate: function() { _validate: function() {
if (this.name != null) throw new Error("name must be null"); if (this.name != null) throw new Error("name must be null");
}, },
}, AST_Lambda); }, AST_Lambda);
var AST_Function = DEFNODE("Function", "inlined", { function is_function(node) {
$documentation: "A function expression", return node instanceof AST_Arrow || node instanceof AST_AsyncFunction || node instanceof AST_Function;
}
var AST_Arrow = DEFNODE("Arrow", "inlined value", {
$documentation: "An arrow function expression",
$propdoc: {
value: "[AST_Node?] simple return expression, or null if using function body.",
},
walk: function(visitor) {
var node = this;
visitor.visit(node, function() {
node.argnames.forEach(function(argname) {
argname.walk(visitor);
});
if (node.value) {
node.value.walk(visitor);
} else {
walk_body(node, visitor);
}
});
},
_validate: function() {
if (this.name != null) throw new Error("name must be null");
if (this.uses_arguments) throw new Error("uses_arguments must be false");
if (this.value != null) {
must_be_expression(this, "value");
if (this.body.length) throw new Error("body must be empty if value exists");
}
},
}, AST_Lambda);
function is_async(node) {
return node instanceof AST_AsyncDefun || node instanceof AST_AsyncFunction;
}
var AST_AsyncFunction = DEFNODE("AsyncFunction", "inlined name", {
$documentation: "An asynchronous function expression",
$propdoc: {
name: "[AST_SymbolLambda?] the name of this function",
},
_validate: function() { _validate: function() {
if (this.name != null) { if (this.name != null) {
if (!(this.name instanceof AST_SymbolLambda)) throw new Error("name must be AST_SymbolLambda"); if (!(this.name instanceof AST_SymbolLambda)) throw new Error("name must be AST_SymbolLambda");
@@ -537,8 +594,37 @@ var AST_Function = DEFNODE("Function", "inlined", {
}, },
}, AST_Lambda); }, AST_Lambda);
var AST_Defun = DEFNODE("Defun", "inlined", { var AST_Function = DEFNODE("Function", "inlined name", {
$documentation: "A function expression",
$propdoc: {
name: "[AST_SymbolLambda?] the name of this function",
},
_validate: function() {
if (this.name != null) {
if (!(this.name instanceof AST_SymbolLambda)) throw new Error("name must be AST_SymbolLambda");
}
},
}, AST_Lambda);
function is_defun(node) {
return node instanceof AST_AsyncDefun || node instanceof AST_Defun;
}
var AST_AsyncDefun = DEFNODE("AsyncDefun", "inlined name", {
$documentation: "An asynchronous function definition",
$propdoc: {
name: "[AST_SymbolDefun] the name of this function",
},
_validate: function() {
if (!(this.name instanceof AST_SymbolDefun)) throw new Error("name must be AST_SymbolDefun");
},
}, AST_Lambda);
var AST_Defun = DEFNODE("Defun", "inlined name", {
$documentation: "A function definition", $documentation: "A function definition",
$propdoc: {
name: "[AST_SymbolDefun] the name of this function",
},
_validate: function() { _validate: function() {
if (!(this.name instanceof AST_SymbolDefun)) throw new Error("name must be AST_SymbolDefun"); if (!(this.name instanceof AST_SymbolDefun)) throw new Error("name must be AST_SymbolDefun");
}, },
@@ -623,7 +709,7 @@ var AST_If = DEFNODE("If", "condition alternative", {
must_be_expression(this, "condition"); must_be_expression(this, "condition");
if (this.alternative != null) { if (this.alternative != null) {
if (!(this.alternative instanceof AST_Statement)) throw new Error("alternative must be AST_Statement"); if (!(this.alternative instanceof AST_Statement)) throw new Error("alternative must be AST_Statement");
if (this.alternative instanceof AST_Function) throw new error("alternative cannot be AST_Function"); if (is_function(this.alternative)) throw new error("alternative cannot be AST_Function");
} }
}, },
}, AST_StatementWithBody); }, AST_StatementWithBody);
@@ -704,19 +790,21 @@ var AST_Try = DEFNODE("Try", "bcatch bfinally", {
var AST_Catch = DEFNODE("Catch", "argname", { var AST_Catch = DEFNODE("Catch", "argname", {
$documentation: "A `catch` node; only makes sense as part of a `try` statement", $documentation: "A `catch` node; only makes sense as part of a `try` statement",
$propdoc: { $propdoc: {
argname: "[AST_SymbolCatch] symbol for the exception" argname: "[(AST_Destructured|AST_SymbolCatch)?] symbol for the exception, or null if not present",
}, },
walk: function(visitor) { walk: function(visitor) {
var node = this; var node = this;
visitor.visit(node, function() { visitor.visit(node, function() {
node.argname.walk(visitor); if (node.argname) node.argname.walk(visitor);
walk_body(node, visitor); walk_body(node, visitor);
}); });
}, },
_validate: function() { _validate: function() {
if (!(this.argname instanceof AST_SymbolCatch)) throw new Error("argname must be AST_SymbolCatch"); if (this.argname != null) validate_destructured(this.argname, function(node) {
if (!(node instanceof AST_SymbolCatch)) throw new Error("argname must be AST_SymbolCatch");
});
}, },
}, AST_BlockScope); }, AST_Block);
var AST_Finally = DEFNODE("Finally", null, { var AST_Finally = DEFNODE("Finally", null, {
$documentation: "A `finally` node; only makes sense as part of a `try` statement" $documentation: "A `finally` node; only makes sense as part of a `try` statement"
@@ -736,14 +824,47 @@ var AST_Definitions = DEFNODE("Definitions", "definitions", {
defn.walk(visitor); defn.walk(visitor);
}); });
}); });
} },
_validate: function() {
if (this.definitions.length < 1) throw new Error("must have at least one definition");
},
}, AST_Statement); }, AST_Statement);
var AST_Const = DEFNODE("Const", null, {
$documentation: "A `const` statement",
_validate: function() {
this.definitions.forEach(function(node) {
if (!(node instanceof AST_VarDef)) throw new Error("definitions must be AST_VarDef[]");
validate_destructured(node.name, function(node) {
if (!(node instanceof AST_SymbolConst)) throw new Error("name must be AST_SymbolConst");
});
if (node.value != null) must_be_expression(node, "value");
});
},
}, AST_Definitions);
var AST_Let = DEFNODE("Let", null, {
$documentation: "A `let` statement",
_validate: function() {
this.definitions.forEach(function(node) {
if (!(node instanceof AST_VarDef)) throw new Error("definitions must be AST_VarDef[]");
validate_destructured(node.name, function(node) {
if (!(node instanceof AST_SymbolLet)) throw new Error("name must be AST_SymbolLet");
});
if (node.value != null) must_be_expression(node, "value");
});
},
}, AST_Definitions);
var AST_Var = DEFNODE("Var", null, { var AST_Var = DEFNODE("Var", null, {
$documentation: "A `var` statement", $documentation: "A `var` statement",
_validate: function() { _validate: function() {
this.definitions.forEach(function(node) { this.definitions.forEach(function(node) {
if (!(node instanceof AST_VarDef)) throw new Error("definitions must be AST_VarDef[]"); if (!(node instanceof AST_VarDef)) throw new Error("definitions must be AST_VarDef[]");
validate_destructured(node.name, function(node) {
if (!(node instanceof AST_SymbolVar)) throw new Error("name must be AST_SymbolVar");
});
if (node.value != null) must_be_expression(node, "value");
}); });
}, },
}, AST_Definitions); }, AST_Definitions);
@@ -751,7 +872,7 @@ var AST_Var = DEFNODE("Var", null, {
var AST_VarDef = DEFNODE("VarDef", "name value", { var AST_VarDef = DEFNODE("VarDef", "name value", {
$documentation: "A variable declaration; only appears in a AST_Definitions node", $documentation: "A variable declaration; only appears in a AST_Definitions node",
$propdoc: { $propdoc: {
name: "[AST_SymbolVar] name of the variable", name: "[AST_Destructured|AST_SymbolVar] name of the variable",
value: "[AST_Node?] initializer, or null of there's no initializer" value: "[AST_Node?] initializer, or null of there's no initializer"
}, },
walk: function(visitor) { walk: function(visitor) {
@@ -761,18 +882,16 @@ var AST_VarDef = DEFNODE("VarDef", "name value", {
if (node.value) node.value.walk(visitor); if (node.value) node.value.walk(visitor);
}); });
}, },
_validate: function() {
if (!(this.name instanceof AST_SymbolVar)) throw new Error("name must be AST_SymbolVar");
if (this.value != null) must_be_expression(this, "value");
},
}); });
/* -----[ OTHER ]----- */ /* -----[ OTHER ]----- */
function must_be_expressions(node, prop) { function must_be_expressions(node, prop, allow_spread, allow_hole) {
node[prop].forEach(function(node) { node[prop].forEach(function(node) {
if (!(node instanceof AST_Node)) throw new Error(prop + " must be AST_Node[]"); if (!(node instanceof AST_Node)) throw new Error(prop + " must be AST_Node[]");
if (node instanceof AST_Statement && !(node instanceof AST_Function)) { if (!allow_hole && node instanceof AST_Hole) throw new Error(prop + " cannot be AST_Hole");
if (!allow_spread && node instanceof AST_Spread) throw new Error(prop + " cannot be AST_Spread");
if (node instanceof AST_Statement && !is_function(node)) {
throw new Error(prop + " cannot contain AST_Statement"); throw new Error(prop + " cannot contain AST_Statement");
} }
}); });
@@ -795,7 +914,7 @@ var AST_Call = DEFNODE("Call", "expression args pure", {
}, },
_validate: function() { _validate: function() {
must_be_expression(this, "expression"); must_be_expression(this, "expression");
must_be_expressions(this, "args"); must_be_expressions(this, "args", true);
}, },
}); });
@@ -872,6 +991,22 @@ var AST_Sub = DEFNODE("Sub", null, {
}, },
}, AST_PropAccess); }, AST_PropAccess);
var AST_Spread = DEFNODE("Spread", "expression", {
$documentation: "Spread expression in array/object literals or function calls",
$propdoc: {
expression: "[AST_Node] expression to be expanded",
},
walk: function(visitor) {
var node = this;
visitor.visit(node, function() {
node.expression.walk(visitor);
});
},
_validate: function() {
must_be_expression(this, "expression");
},
});
var AST_Unary = DEFNODE("Unary", "operator expression", { var AST_Unary = DEFNODE("Unary", "operator expression", {
$documentation: "Base class for unary expressions", $documentation: "Base class for unary expressions",
$propdoc: { $propdoc: {
@@ -945,9 +1080,33 @@ var AST_Assign = DEFNODE("Assign", null, {
$documentation: "An assignment expression — `a = b + 5`", $documentation: "An assignment expression — `a = b + 5`",
_validate: function() { _validate: function() {
if (this.operator.indexOf("=") < 0) throw new Error('operator must contain "="'); if (this.operator.indexOf("=") < 0) throw new Error('operator must contain "="');
if (this.left instanceof AST_Destructured) {
if (this.operator != "=") throw new Error("invalid destructuring operator: " + this.operator);
validate_destructured(this.left, function(node) {
if (!(node instanceof AST_PropAccess || node instanceof AST_SymbolRef)) {
throw new Error("left must be assignable: " + node.TYPE);
}
});
}
}, },
}, AST_Binary); }, AST_Binary);
var AST_Await = DEFNODE("Await", "expression", {
$documentation: "An await expression",
$propdoc: {
expression: "[AST_Node] expression with Promise to resolve on",
},
walk: function(visitor) {
var node = this;
visitor.visit(node, function() {
node.expression.walk(visitor);
});
},
_validate: function() {
must_be_expression(this, "expression");
},
});
/* -----[ LITERALS ]----- */ /* -----[ LITERALS ]----- */
var AST_Array = DEFNODE("Array", "elements", { var AST_Array = DEFNODE("Array", "elements", {
@@ -964,14 +1123,65 @@ var AST_Array = DEFNODE("Array", "elements", {
}); });
}, },
_validate: function() { _validate: function() {
must_be_expressions(this, "elements"); must_be_expressions(this, "elements", true, true);
}, },
}); });
var AST_Object = DEFNODE("Object", "properties", { var AST_Destructured = DEFNODE("Destructured", null, {
$documentation: "An object literal", $documentation: "Base class for destructured literal",
});
function validate_destructured(node, check) {
if (node instanceof AST_DestructuredArray) return node.elements.forEach(function(node) {
if (!(node instanceof AST_Hole)) validate_destructured(node, check);
});
if (node instanceof AST_DestructuredObject) return node.properties.forEach(function(prop) {
validate_destructured(prop.value, check);
});
check(node);
}
var AST_DestructuredArray = DEFNODE("DestructuredArray", "elements", {
$documentation: "A destructured array literal",
$propdoc: { $propdoc: {
properties: "[AST_ObjectProperty*] array of properties" elements: "[AST_Node*] array of elements",
},
walk: function(visitor) {
var node = this;
visitor.visit(node, function() {
node.elements.forEach(function(element) {
element.walk(visitor);
});
});
},
}, AST_Destructured);
var AST_DestructuredKeyVal = DEFNODE("DestructuredKeyVal", "key value", {
$documentation: "A key: value destructured property",
$propdoc: {
key: "[string|AST_Node] property name. For computed property this is an AST_Node.",
value: "[AST_Node] property value",
},
walk: function(visitor) {
var node = this;
visitor.visit(node, function() {
if (node.key instanceof AST_Node) node.key.walk(visitor);
node.value.walk(visitor);
});
},
_validate: function() {
if (typeof this.key != "string") {
if (!(this.key instanceof AST_Node)) throw new Error("key must be string or AST_Node");
must_be_expression(this, "key");
}
must_be_expression(this, "value");
},
});
var AST_DestructuredObject = DEFNODE("DestructuredObject", "properties", {
$documentation: "A destructured object literal",
$propdoc: {
properties: "[AST_DestructuredKeyVal*] array of properties",
}, },
walk: function(visitor) { walk: function(visitor) {
var node = this; var node = this;
@@ -983,7 +1193,29 @@ var AST_Object = DEFNODE("Object", "properties", {
}, },
_validate: function() { _validate: function() {
this.properties.forEach(function(node) { this.properties.forEach(function(node) {
if (!(node instanceof AST_ObjectProperty)) throw new Error("properties must be AST_ObjectProperty[]"); if (!(node instanceof AST_DestructuredKeyVal)) throw new Error("properties must be AST_DestructuredKeyVal[]");
});
},
}, AST_Destructured);
var AST_Object = DEFNODE("Object", "properties", {
$documentation: "An object literal",
$propdoc: {
properties: "[(AST_ObjectProperty|AST_Spread)*] array of properties"
},
walk: function(visitor) {
var node = this;
visitor.visit(node, function() {
node.properties.forEach(function(prop) {
prop.walk(visitor);
});
});
},
_validate: function() {
this.properties.forEach(function(node) {
if (!(node instanceof AST_ObjectProperty || node instanceof AST_Spread)) {
throw new Error("properties must contain AST_ObjectProperty and/or AST_Spread only");
}
}); });
}, },
}); });
@@ -991,24 +1223,28 @@ var AST_Object = DEFNODE("Object", "properties", {
var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", { var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", {
$documentation: "Base class for literal object properties", $documentation: "Base class for literal object properties",
$propdoc: { $propdoc: {
key: "[string|AST_SymbolAccessor] property name. For ObjectKeyVal this is a string. For getters and setters this is an AST_SymbolAccessor.", key: "[string|AST_Node] property name. For computed property this is an AST_Node.",
value: "[AST_Node] property value. For getters and setters this is an AST_Accessor." value: "[AST_Node] property value. For getters and setters this is an AST_Accessor.",
}, },
walk: function(visitor) { walk: function(visitor) {
var node = this; var node = this;
visitor.visit(node, function() { visitor.visit(node, function() {
if (node.key instanceof AST_Node) node.key.walk(visitor);
node.value.walk(visitor); node.value.walk(visitor);
}); });
}
});
var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", "quote", {
$documentation: "A key: value object property",
$propdoc: {
quote: "[string] the original quote character"
}, },
_validate: function() { _validate: function() {
if (typeof this.key != "string") throw new Error("key must be string"); if (typeof this.key != "string") {
if (!(this.key instanceof AST_Node)) throw new Error("key must be string or AST_Node");
must_be_expression(this, "key");
}
if (!(this.value instanceof AST_Node)) throw new Error("value must be AST_Node");
},
});
var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", null, {
$documentation: "A key: value object property",
_validate: function() {
must_be_expression(this, "value"); must_be_expression(this, "value");
}, },
}, AST_ObjectProperty); }, AST_ObjectProperty);
@@ -1016,7 +1252,6 @@ var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", "quote", {
var AST_ObjectSetter = DEFNODE("ObjectSetter", null, { var AST_ObjectSetter = DEFNODE("ObjectSetter", null, {
$documentation: "An object setter property", $documentation: "An object setter property",
_validate: function() { _validate: function() {
if (!(this.key instanceof AST_SymbolAccessor)) throw new Error("key must be AST_SymbolAccessor");
if (!(this.value instanceof AST_Accessor)) throw new Error("value must be AST_Accessor"); if (!(this.value instanceof AST_Accessor)) throw new Error("value must be AST_Accessor");
}, },
}, AST_ObjectProperty); }, AST_ObjectProperty);
@@ -1024,31 +1259,34 @@ var AST_ObjectSetter = DEFNODE("ObjectSetter", null, {
var AST_ObjectGetter = DEFNODE("ObjectGetter", null, { var AST_ObjectGetter = DEFNODE("ObjectGetter", null, {
$documentation: "An object getter property", $documentation: "An object getter property",
_validate: function() { _validate: function() {
if (!(this.key instanceof AST_SymbolAccessor)) throw new Error("key must be AST_SymbolAccessor");
if (!(this.value instanceof AST_Accessor)) throw new Error("value must be AST_Accessor"); if (!(this.value instanceof AST_Accessor)) throw new Error("value must be AST_Accessor");
}, },
}, AST_ObjectProperty); }, AST_ObjectProperty);
var AST_Symbol = DEFNODE("Symbol", "scope name thedef", { var AST_Symbol = DEFNODE("Symbol", "scope name thedef", {
$documentation: "Base class for all symbols",
$propdoc: { $propdoc: {
name: "[string] name of this symbol", name: "[string] name of this symbol",
scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)", scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)",
thedef: "[SymbolDef/S] the definition of this symbol" thedef: "[SymbolDef/S] the definition of this symbol"
}, },
$documentation: "Base class for all symbols",
_validate: function() { _validate: function() {
if (typeof this.name != "string") throw new Error("name must be string"); if (typeof this.name != "string") throw new Error("name must be string");
}, },
}); });
var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, {
$documentation: "The name of a property accessor (setter/getter function)"
}, AST_Symbol);
var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", { var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", {
$documentation: "A declaration symbol (symbol in var, function name or argument, symbol in catch)", $documentation: "A declaration symbol (symbol in var, function name or argument, symbol in catch)",
}, AST_Symbol); }, AST_Symbol);
var AST_SymbolConst = DEFNODE("SymbolConst", null, {
$documentation: "Symbol defining a constant",
}, AST_SymbolDeclaration);
var AST_SymbolLet = DEFNODE("SymbolLet", null, {
$documentation: "Symbol defining a lexical-scoped variable",
}, AST_SymbolDeclaration);
var AST_SymbolVar = DEFNODE("SymbolVar", null, { var AST_SymbolVar = DEFNODE("SymbolVar", null, {
$documentation: "Symbol defining a variable", $documentation: "Symbol defining a variable",
}, AST_SymbolDeclaration); }, AST_SymbolDeclaration);
@@ -1080,7 +1318,7 @@ var AST_Label = DEFNODE("Label", "references", {
} }
}, AST_Symbol); }, AST_Symbol);
var AST_SymbolRef = DEFNODE("SymbolRef", "fixed", { var AST_SymbolRef = DEFNODE("SymbolRef", "fixed in_arg", {
$documentation: "Reference to some symbol (not definition/declaration)", $documentation: "Reference to some symbol (not definition/declaration)",
}, AST_Symbol); }, AST_Symbol);
@@ -1256,14 +1494,13 @@ TreeWalker.prototype = {
|| p.tail_node() === self) { || p.tail_node() === self) {
self = p; self = p;
} else if (p instanceof AST_Return) { } else if (p instanceof AST_Return) {
var fn; for (var call, fn = p; call = this.parent(++i); fn = call) {
do { if (call.TYPE == "Call") {
fn = this.parent(++i); if (!(fn instanceof AST_Lambda) || fn.name) return false;
if (!fn) return false; } else if (fn instanceof AST_Lambda) {
} while (!(fn instanceof AST_Lambda)); return false;
if (fn.name) return false; }
self = this.parent(++i); }
if (!self || self.TYPE != "Call" || self.expression !== fn) return false;
} else { } else {
return false; return false;
} }

File diff suppressed because it is too large Load Diff

View File

@@ -33,7 +33,9 @@ function read_source_map(name, toplevel) {
return to_ascii(match[2]); return to_ascii(match[2]);
} }
} }
AST_Node.warn("inline source map not found: " + name); AST_Node.warn("inline source map not found: {name}", {
name: name,
});
} }
function parse_source_map(content) { function parse_source_map(content) {
@@ -87,6 +89,7 @@ function minify(files, options) {
toplevel: false, toplevel: false,
validate: false, validate: false,
warnings: false, warnings: false,
webkit: false,
wrap: false, wrap: false,
}, true); }, true);
if (options.validate) AST_Node.enable_validation(); if (options.validate) AST_Node.enable_validation();
@@ -99,6 +102,7 @@ function minify(files, options) {
set_shorthand("ie8", options, [ "compress", "mangle", "output" ]); set_shorthand("ie8", options, [ "compress", "mangle", "output" ]);
set_shorthand("keep_fnames", options, [ "compress", "mangle" ]); set_shorthand("keep_fnames", options, [ "compress", "mangle" ]);
set_shorthand("toplevel", options, [ "compress", "mangle" ]); set_shorthand("toplevel", options, [ "compress", "mangle" ]);
set_shorthand("webkit", options, [ "mangle", "output" ]);
var quoted_props; var quoted_props;
if (options.mangle) { if (options.mangle) {
options.mangle = defaults(options.mangle, { options.mangle = defaults(options.mangle, {
@@ -109,6 +113,7 @@ function minify(files, options) {
properties: false, properties: false,
reserved: [], reserved: [],
toplevel: false, toplevel: false,
webkit: false,
}, true); }, true);
if (options.mangle.properties) { if (options.mangle.properties) {
if (typeof options.mangle.properties != "object") { if (typeof options.mangle.properties != "object") {
@@ -258,6 +263,7 @@ function minify(files, options) {
} catch (ex) { } catch (ex) {
return { error: ex }; return { error: ex };
} finally { } finally {
AST_Node.log_function();
AST_Node.disable_validation(); AST_Node.disable_validation();
} }
} }

View File

@@ -115,9 +115,6 @@
value : from_moz(M.value) value : from_moz(M.value)
}; };
if (M.kind == "init") return new AST_ObjectKeyVal(args); if (M.kind == "init") return new AST_ObjectKeyVal(args);
args.key = new AST_SymbolAccessor({
name: args.key
});
args.value = new AST_Accessor(args.value); args.value = new AST_Accessor(args.value);
if (M.kind == "get") return new AST_ObjectGetter(args); if (M.kind == "get") return new AST_ObjectGetter(args);
if (M.kind == "set") return new AST_ObjectSetter(args); if (M.kind == "set") return new AST_ObjectSetter(args);
@@ -385,7 +382,7 @@
def_to_moz(AST_ObjectProperty, function To_Moz_Property(M) { def_to_moz(AST_ObjectProperty, function To_Moz_Property(M) {
var key = { var key = {
type: "Literal", type: "Literal",
value: M.key instanceof AST_SymbolAccessor ? M.key.name : M.key value: M.key
}; };
var kind; var kind;
if (M instanceof AST_ObjectKeyVal) { if (M instanceof AST_ObjectKeyVal) {

View File

@@ -56,6 +56,7 @@ function OutputStream(options) {
beautify : false, beautify : false,
braces : false, braces : false,
comments : false, comments : false,
galio : false,
ie8 : false, ie8 : false,
indent_level : 4, indent_level : 4,
indent_start : 0, indent_start : 0,
@@ -69,6 +70,7 @@ function OutputStream(options) {
semicolons : true, semicolons : true,
shebang : true, shebang : true,
source_map : null, source_map : null,
v8 : false,
webkit : false, webkit : false,
width : 80, width : 80,
wrap_iife : false, wrap_iife : false,
@@ -107,6 +109,9 @@ function OutputStream(options) {
var OUTPUT = ""; var OUTPUT = "";
var to_utf8 = options.ascii_only ? function(str, identifier) { var to_utf8 = options.ascii_only ? function(str, identifier) {
if (identifier) str = str.replace(/[\ud800-\udbff][\udc00-\udfff]/g, function(ch) {
return "\\u{" + (ch.charCodeAt(0) - 0xd7c0 << 10 | ch.charCodeAt(1) - 0xdc00).toString(16) + "}";
});
return str.replace(/[\u0000-\u001f\u007f-\uffff]/g, function(ch) { return str.replace(/[\u0000-\u001f\u007f-\uffff]/g, function(ch) {
var code = ch.charCodeAt(0).toString(16); var code = ch.charCodeAt(0).toString(16);
if (code.length <= 2 && !identifier) { if (code.length <= 2 && !identifier) {
@@ -496,11 +501,11 @@ function OutputStream(options) {
} }
} }
if (/comment[134]/.test(c.type)) { if (/comment[134]/.test(c.type)) {
print("//" + c.value.replace(/[@#]__PURE__/g, ' ') + "\n"); print("//" + c.value.replace(/[@#]__PURE__/g, " ") + "\n");
indent(); indent();
last_nlb = true; last_nlb = true;
} else if (c.type == "comment2") { } else if (c.type == "comment2") {
print("/*" + c.value.replace(/[@#]__PURE__/g, ' ') + "*/"); print("/*" + c.value.replace(/[@#]__PURE__/g, " ") + "*/");
last_nlb = false; last_nlb = false;
} }
}); });
@@ -554,10 +559,10 @@ function OutputStream(options) {
space(); space();
} }
if (/comment[134]/.test(c.type)) { if (/comment[134]/.test(c.type)) {
print("//" + c.value.replace(/[@#]__PURE__/g, ' ')); print("//" + c.value.replace(/[@#]__PURE__/g, " "));
need_newline_indented = true; need_newline_indented = true;
} else if (c.type == "comment2") { } else if (c.type == "comment2") {
print("/*" + c.value.replace(/[@#]__PURE__/g, ' ') + "*/"); print("/*" + c.value.replace(/[@#]__PURE__/g, " ") + "*/");
need_space = true; need_space = true;
} }
}); });
@@ -607,7 +612,7 @@ function OutputStream(options) {
}, },
parent : function(n) { parent : function(n) {
return stack[stack.length - 2 - (n || 0)]; return stack[stack.length - 2 - (n || 0)];
} },
}; };
} }
@@ -649,36 +654,33 @@ function OutputStream(options) {
/* -----[ PARENTHESES ]----- */ /* -----[ PARENTHESES ]----- */
function PARENS(nodetype, func) { function PARENS(nodetype, func) {
if (Array.isArray(nodetype)) { nodetype.DEFMETHOD("needs_parens", func);
nodetype.forEach(function(nodetype) {
PARENS(nodetype, func);
});
} else {
nodetype.DEFMETHOD("needs_parens", func);
}
} }
PARENS(AST_Node, return_false); PARENS(AST_Node, return_false);
// a function expression needs parens around it when it's provably // a function expression needs parens around it when it's provably
// the first token to appear in a statement. // the first token to appear in a statement.
PARENS(AST_Function, function(output) { function needs_parens_function(output) {
if (!output.has_parens() && first_in_statement(output)) return true; if (!output.has_parens() && first_in_statement(output)) return true;
if (output.option('webkit')) { if (output.option("webkit")) {
var p = output.parent(); var p = output.parent();
if (p instanceof AST_PropAccess && p.expression === this) return true; if (p instanceof AST_PropAccess && p.expression === this) return true;
} }
if (output.option('wrap_iife')) { if (output.option("wrap_iife")) {
var p = output.parent(); var p = output.parent();
if (p instanceof AST_Call && p.expression === this) return true; if (p instanceof AST_Call && p.expression === this) return true;
} }
}); }
PARENS(AST_AsyncFunction, needs_parens_function);
PARENS(AST_Function, needs_parens_function);
// same goes for an object literal, because otherwise it would be // same goes for an object literal, because otherwise it would be
// interpreted as a block of code. // interpreted as a block of code.
PARENS(AST_Object, function(output) { function needs_parens_obj(output) {
return !output.has_parens() && first_in_statement(output); return !output.has_parens() && first_in_statement(output, true);
}); }
PARENS(AST_Object, needs_parens_obj);
PARENS(AST_Unary, function(output) { PARENS(AST_Unary, function(output) {
var p = output.parent(); var p = output.parent();
@@ -689,6 +691,10 @@ function OutputStream(options) {
var p = output.parent(); var p = output.parent();
// [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ] // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ]
return p instanceof AST_Array return p instanceof AST_Array
// () => (foo, bar)
|| p instanceof AST_Arrow && p.value === this
// await (foo, bar)
|| p instanceof AST_Await
// 1 + (2, 3) + 4 ==> 8 // 1 + (2, 3) + 4 ==> 8
|| p instanceof AST_Binary || p instanceof AST_Binary
// new (foo, bar) or foo(1, (2, 3), 4) // new (foo, bar) or foo(1, (2, 3), 4)
@@ -696,10 +702,14 @@ function OutputStream(options) {
// (false, true) ? (a = 10, b = 20) : (c = 30) // (false, true) ? (a = 10, b = 20) : (c = 30)
// ==> 20 (side effect, set a := 10 and b := 20) // ==> 20 (side effect, set a := 10 and b := 20)
|| p instanceof AST_Conditional || p instanceof AST_Conditional
// { [(1, 2)]: 3 }[2] ==> 3
// { foo: (1, 2) }.foo ==> 2 // { foo: (1, 2) }.foo ==> 2
|| p instanceof AST_DestructuredKeyVal
|| p instanceof AST_ObjectProperty || p instanceof AST_ObjectProperty
// (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2 // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2
|| p instanceof AST_PropAccess && p.expression === this || p instanceof AST_PropAccess && p.expression === this
// ...(foo, bar, baz)
|| p instanceof AST_Spread
// !(foo, bar, baz) // !(foo, bar, baz)
|| p instanceof AST_Unary || p instanceof AST_Unary
// var a = (1, 2), b = a + a; ==> b == 4 // var a = (1, 2), b = a + a; ==> b == 4
@@ -708,6 +718,8 @@ function OutputStream(options) {
PARENS(AST_Binary, function(output) { PARENS(AST_Binary, function(output) {
var p = output.parent(); var p = output.parent();
// await (foo && bar)
if (p instanceof AST_Await) return true;
// this deals with precedence: 3 * (2 + 1) // this deals with precedence: 3 * (2 + 1)
if (p instanceof AST_Binary) { if (p instanceof AST_Binary) {
var po = p.operator, pp = PRECEDENCE[po]; var po = p.operator, pp = PRECEDENCE[po];
@@ -743,7 +755,7 @@ function OutputStream(options) {
var p = output.parent(); var p = output.parent();
if (p instanceof AST_New) return p.expression === this; if (p instanceof AST_New) return p.expression === this;
// https://bugs.webkit.org/show_bug.cgi?id=123506 // https://bugs.webkit.org/show_bug.cgi?id=123506
if (output.option('webkit')) { if (output.option("webkit")) {
var g = output.parent(1); var g = output.parent(1);
return this.expression instanceof AST_Function return this.expression instanceof AST_Function
&& p instanceof AST_PropAccess && p instanceof AST_PropAccess
@@ -766,24 +778,51 @@ function OutputStream(options) {
var p = output.parent(); var p = output.parent();
if (p instanceof AST_PropAccess && p.expression === this) { if (p instanceof AST_PropAccess && p.expression === this) {
var value = this.value; var value = this.value;
// https://github.com/mishoo/UglifyJS/issues/115 // https://github.com/mishoo/UglifyJS/issues/115
// https://github.com/mishoo/UglifyJS/pull/1009 return value < 0
return value < 0 || /^0/.test(make_num(value)); // https://github.com/mishoo/UglifyJS/pull/1009
|| output.option("galio") && /^0/.test(make_num(value));
} }
}); });
PARENS([ AST_Assign, AST_Conditional ], function(output) { function needs_parens_assign_cond(self, output) {
var p = output.parent(); var p = output.parent();
// await (a = foo)
if (p instanceof AST_Await) return true;
// 1 + (a = 2) + 3 → 6, side effect setting a = 2 // 1 + (a = 2) + 3 → 6, side effect setting a = 2
if (p instanceof AST_Binary) return !(p instanceof AST_Assign); if (p instanceof AST_Binary) return !(p instanceof AST_Assign);
// (a = func)() —or— new (a = Object)() // (a = func)() —or— new (a = Object)()
if (p instanceof AST_Call) return p.expression === this; if (p instanceof AST_Call) return p.expression === self;
// (a = foo) ? bar : baz // (a = foo) ? bar : baz
if (p instanceof AST_Conditional) return p.condition === this; if (p instanceof AST_Conditional) return p.condition === self;
// (a = foo)["prop"] —or— (a = foo).prop // (a = foo)["prop"] —or— (a = foo).prop
if (p instanceof AST_PropAccess) return p.expression === this; if (p instanceof AST_PropAccess) return p.expression === self;
// !(a = false) → true // !(a = false) → true
if (p instanceof AST_Unary) return true; if (p instanceof AST_Unary) return true;
}
PARENS(AST_Arrow, function(output) {
return needs_parens_assign_cond(this, output);
});
PARENS(AST_Assign, function(output) {
if (needs_parens_assign_cond(this, output)) return true;
// v8 parser bug => workaround
// f([1], [a] = []) => f([1], ([a] = []))
if (output.option("v8")) return this.left instanceof AST_Destructured;
// ({ p: a } = o);
if (this.left instanceof AST_DestructuredObject) return needs_parens_obj(output);
});
PARENS(AST_Conditional, function(output) {
return needs_parens_assign_cond(this, output);
});
PARENS(AST_Await, function(output) {
var p = output.parent();
// new (await foo)
// (await foo)(bar)
if (p instanceof AST_Call) return p.expression === this;
// (await foo).prop
// (await foo)["prop"]
if (p instanceof AST_PropAccess) return p.expression === this;
}); });
/* -----[ PRINTERS ]----- */ /* -----[ PRINTERS ]----- */
@@ -835,10 +874,6 @@ function OutputStream(options) {
use_asm = was_asm; use_asm = was_asm;
} }
AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output) {
force_statement(this.body, output);
});
DEFPRINT(AST_Statement, function(output) { DEFPRINT(AST_Statement, function(output) {
this.body.print(output); this.body.print(output);
output.semicolon(); output.semicolon();
@@ -897,7 +932,7 @@ function OutputStream(options) {
self.condition.print(output); self.condition.print(output);
}); });
output.space(); output.space();
self._do_print_body(output); force_statement(self.body, output);
}); });
DEFPRINT(AST_For, function(output) { DEFPRINT(AST_For, function(output) {
var self = this; var self = this;
@@ -927,7 +962,7 @@ function OutputStream(options) {
} }
}); });
output.space(); output.space();
self._do_print_body(output); force_statement(self.body, output);
}); });
DEFPRINT(AST_ForIn, function(output) { DEFPRINT(AST_ForIn, function(output) {
var self = this; var self = this;
@@ -941,7 +976,7 @@ function OutputStream(options) {
self.object.print(output); self.object.print(output);
}); });
output.space(); output.space();
self._do_print_body(output); force_statement(self.body, output);
}); });
DEFPRINT(AST_With, function(output) { DEFPRINT(AST_With, function(output) {
var self = this; var self = this;
@@ -951,15 +986,30 @@ function OutputStream(options) {
self.expression.print(output); self.expression.print(output);
}); });
output.space(); output.space();
self._do_print_body(output); force_statement(self.body, output);
}); });
/* -----[ functions ]----- */ /* -----[ functions ]----- */
DEFPRINT(AST_Lambda, function(output, nokeyword) { DEFPRINT(AST_Arrow, function(output) {
var self = this; var self = this;
if (!nokeyword) { if (self.argnames.length == 1 && self.argnames[0] instanceof AST_SymbolFunarg) {
output.print("function"); self.argnames[0].print(output);
} else output.with_parens(function() {
self.argnames.forEach(function(arg, i) {
if (i) output.comma();
arg.print(output);
});
});
output.space();
output.print("=>");
output.space();
if (self.value) {
self.value.print(output);
} else {
print_braced(self, output, true);
} }
});
function print_lambda(self, output) {
if (self.name) { if (self.name) {
output.space(); output.space();
self.name.print(output); self.name.print(output);
@@ -972,7 +1022,19 @@ function OutputStream(options) {
}); });
output.space(); output.space();
print_braced(self, output, true); print_braced(self, output, true);
}
DEFPRINT(AST_Lambda, function(output) {
output.print("function");
print_lambda(this, output);
}); });
function print_async(output) {
output.print("async");
output.space();
output.print("function");
print_lambda(this, output);
}
DEFPRINT(AST_AsyncDefun, print_async);
DEFPRINT(AST_AsyncFunction, print_async);
/* -----[ jumps ]----- */ /* -----[ jumps ]----- */
function print_jump(kind, prop) { function print_jump(kind, prop) {
@@ -994,7 +1056,7 @@ function OutputStream(options) {
/* -----[ if ]----- */ /* -----[ if ]----- */
function make_then(self, output) { function make_then(self, output) {
var b = self.body; var b = self.body;
if (output.option("braces") if (output.option("braces") && !(b instanceof AST_Const || b instanceof AST_Let)
|| output.option("ie8") && b instanceof AST_Do) || output.option("ie8") && b instanceof AST_Do)
return make_block(b, output); return make_block(b, output);
// The squeezer replaces "block"-s that contain only a single // The squeezer replaces "block"-s that contain only a single
@@ -1036,7 +1098,7 @@ function OutputStream(options) {
else else
force_statement(self.alternative, output); force_statement(self.alternative, output);
} else { } else {
self._do_print_body(output); force_statement(self.body, output);
} }
}); });
@@ -1099,10 +1161,12 @@ function OutputStream(options) {
DEFPRINT(AST_Catch, function(output) { DEFPRINT(AST_Catch, function(output) {
var self = this; var self = this;
output.print("catch"); output.print("catch");
output.space(); if (self.argname) {
output.with_parens(function() { output.space();
self.argname.print(output); output.with_parens(function() {
}); self.argname.print(output);
});
}
output.space(); output.space();
print_braced(self, output); print_braced(self, output);
}); });
@@ -1112,28 +1176,31 @@ function OutputStream(options) {
print_braced(this, output); print_braced(this, output);
}); });
DEFPRINT(AST_Var, function(output) { function print_definitinos(type) {
var self = this; return function(output) {
output.print("var"); var self = this;
output.space(); output.print(type);
self.definitions.forEach(function(def, i) { output.space();
if (i) output.comma(); self.definitions.forEach(function(def, i) {
def.print(output); if (i) output.comma();
}); def.print(output);
var p = output.parent(); });
if (p && p.init !== self || !(p instanceof AST_For || p instanceof AST_ForIn)) output.semicolon(); var p = output.parent();
}); if (p && p.init !== self || !(p instanceof AST_For || p instanceof AST_ForIn)) output.semicolon();
};
}
DEFPRINT(AST_Const, print_definitinos("const"));
DEFPRINT(AST_Let, print_definitinos("let"));
DEFPRINT(AST_Var, print_definitinos("var"));
function parenthesize_for_noin(node, output, noin) { function parenthesize_for_noin(node, output, noin) {
var parens = false; var parens = false;
// need to take some precautions here: // need to take some precautions here:
// https://github.com/mishoo/UglifyJS/issues/60 // https://github.com/mishoo/UglifyJS/issues/60
if (noin) node.walk(new TreeWalker(function(node) { if (noin) node.walk(new TreeWalker(function(node) {
if (parens || node instanceof AST_Scope) return true; if (parens) return true;
if (node instanceof AST_Binary && node.operator == "in") { if (node instanceof AST_Binary && node.operator == "in") return parens = true;
parens = true; if (node instanceof AST_Scope && !(node instanceof AST_Arrow && node.value)) return true;
return true;
}
})); }));
node.print(output, parens); node.print(output, parens);
} }
@@ -1214,6 +1281,10 @@ function OutputStream(options) {
this.property.print(output); this.property.print(output);
output.print("]"); output.print("]");
}); });
DEFPRINT(AST_Spread, function(output) {
output.print("...");
this.expression.print(output);
});
DEFPRINT(AST_UnaryPrefix, function(output) { DEFPRINT(AST_UnaryPrefix, function(output) {
var op = this.operator; var op = this.operator;
var exp = this.expression; var exp = this.expression;
@@ -1249,6 +1320,11 @@ function OutputStream(options) {
output.colon(); output.colon();
self.alternative.print(output); self.alternative.print(output);
}); });
DEFPRINT(AST_Await, function(output) {
output.print("await");
output.space();
this.expression.print(output);
});
/* -----[ literals ]----- */ /* -----[ literals ]----- */
DEFPRINT(AST_Array, function(output) { DEFPRINT(AST_Array, function(output) {
@@ -1267,6 +1343,38 @@ function OutputStream(options) {
output.space(); output.space();
} : noop); } : noop);
}); });
DEFPRINT(AST_DestructuredArray, function(output) {
var a = this.elements, len = a.length;
output.with_square(len > 0 ? function() {
output.space();
a.forEach(function(exp, i) {
if (i) output.comma();
exp.print(output);
// If the final element is a hole, we need to make sure it
// doesn't look like a trailing comma, by inserting an actual
// trailing comma.
if (i === len - 1 && exp instanceof AST_Hole)
output.comma();
});
output.space();
} : noop);
});
DEFPRINT(AST_DestructuredKeyVal, print_key_value);
DEFPRINT(AST_DestructuredObject, function(output) {
var props = this.properties;
if (props.length > 0) output.with_block(function() {
props.forEach(function(prop, i) {
if (i) {
output.print(",");
output.newline();
}
output.indent();
prop.print(output);
});
output.newline();
});
else print_braced_empty(this, output);
});
DEFPRINT(AST_Object, function(output) { DEFPRINT(AST_Object, function(output) {
var props = this.properties; var props = this.properties;
if (props.length > 0) output.with_block(function() { if (props.length > 0) output.with_block(function() {
@@ -1283,35 +1391,44 @@ function OutputStream(options) {
else print_braced_empty(this, output); else print_braced_empty(this, output);
}); });
function print_property_name(key, quote, output) { function print_property_key(self, output) {
if (output.option("quote_keys")) { var key = self.key;
if (key instanceof AST_Node) {
output.with_square(function() {
key.print(output);
});
} else if (output.option("quote_keys")) {
output.print_string(key); output.print_string(key);
} else if ("" + +key == key && key >= 0) { } else if ("" + +key == key && key >= 0) {
output.print(make_num(key)); output.print(make_num(key));
} else if (RESERVED_WORDS[key] ? !output.option("ie8") : is_identifier_string(key)) {
if (quote && output.option("keep_quoted_props")) {
output.print_string(key, quote);
} else {
output.print_name(key);
}
} else { } else {
output.print_string(key, quote); var quote = self.start && self.start.quote;
if (RESERVED_WORDS[key] ? !output.option("ie8") : is_identifier_string(key)) {
if (quote && output.option("keep_quoted_props")) {
output.print_string(key, quote);
} else {
output.print_name(key);
}
} else {
output.print_string(key, quote);
}
} }
} }
DEFPRINT(AST_ObjectKeyVal, function(output) { function print_key_value(output) {
var self = this; var self = this;
print_property_name(self.key, self.quote, output); print_property_key(self, output);
output.colon(); output.colon();
self.value.print(output); self.value.print(output);
}); }
DEFPRINT(AST_ObjectKeyVal, print_key_value);
function print_accessor(type) { function print_accessor(type) {
return function(output) { return function(output) {
var self = this; var self = this;
output.print(type); output.print(type);
output.space(); output.space();
print_property_name(self.key.name, self.quote, output); print_property_key(self, output);
self.value._codegen(output, true); print_lambda(self.value, output);
}; };
} }
DEFPRINT(AST_ObjectGetter, print_accessor("get")); DEFPRINT(AST_ObjectGetter, print_accessor("get"));
@@ -1379,13 +1496,12 @@ function OutputStream(options) {
}); });
function force_statement(stat, output) { function force_statement(stat, output) {
if (output.option("braces")) { if (output.option("braces") && !(stat instanceof AST_Const || stat instanceof AST_Let)) {
make_block(stat, output); make_block(stat, output);
} else if (!stat || stat instanceof AST_EmptyStatement) {
output.force_semicolon();
} else { } else {
if (!stat || stat instanceof AST_EmptyStatement) stat.print(output);
output.force_semicolon();
else
stat.print(output);
} }
} }
@@ -1469,6 +1585,7 @@ function OutputStream(options) {
AST_Constant, AST_Constant,
AST_Debugger, AST_Debugger,
AST_Definitions, AST_Definitions,
AST_Destructured,
AST_Finally, AST_Finally,
AST_Jump, AST_Jump,
AST_Lambda, AST_Lambda,
@@ -1483,14 +1600,7 @@ function OutputStream(options) {
output.add_mapping(this.start); output.add_mapping(this.start);
}); });
DEFMAP([ DEFMAP([ AST_DestructuredKeyVal, AST_ObjectProperty ], function(output) {
AST_ObjectGetter, if (typeof this.key == "string") output.add_mapping(this.start, this.key);
AST_ObjectSetter,
], function(output) {
output.add_mapping(this.start, this.key.name);
});
DEFMAP([ AST_ObjectProperty ], function(output) {
output.add_mapping(this.start, this.key);
}); });
})(); })();

File diff suppressed because it is too large Load Diff

View File

@@ -81,8 +81,8 @@ var builtins = function() {
function reserve_quoted_keys(ast, reserved) { function reserve_quoted_keys(ast, reserved) {
ast.walk(new TreeWalker(function(node) { ast.walk(new TreeWalker(function(node) {
if (node instanceof AST_ObjectKeyVal) { if (node instanceof AST_ObjectProperty) {
if (node.quote) add(node.key); if (node.start && node.start.quote) add(node.key);
} else if (node instanceof AST_Sub) { } else if (node instanceof AST_Sub) {
addStrings(node.property, add); addStrings(node.property, add);
} }
@@ -165,11 +165,8 @@ function mangle_properties(ast, options) {
} }
} else if (node instanceof AST_Dot) { } else if (node instanceof AST_Dot) {
add(node.property); add(node.property);
} else if (node instanceof AST_ObjectKeyVal) {
add(node.key);
} else if (node instanceof AST_ObjectProperty) { } else if (node instanceof AST_ObjectProperty) {
// setter or getter, since KeyVal is handled above if (typeof node.key == "string") add(node.key);
add(node.key.name);
} else if (node instanceof AST_Sub) { } else if (node instanceof AST_Sub) {
addStrings(node.property, add); addStrings(node.property, add);
} }
@@ -198,11 +195,8 @@ function mangle_properties(ast, options) {
} }
} else if (node instanceof AST_Dot) { } else if (node instanceof AST_Dot) {
node.property = mangle(node.property); node.property = mangle(node.property);
} else if (node instanceof AST_ObjectKeyVal) {
node.key = mangle(node.key);
} else if (node instanceof AST_ObjectProperty) { } else if (node instanceof AST_ObjectProperty) {
// setter or getter if (typeof node.key == "string") node.key = mangle(node.key);
node.key.name = mangle(node.key.name);
} else if (node instanceof AST_Sub) { } else if (node instanceof AST_Sub) {
if (!options.keep_quoted) mangleStrings(node.property); if (!options.keep_quoted) mangleStrings(node.property);
} }

View File

@@ -68,11 +68,11 @@ SymbolDef.prototype = {
if (this.global && cache && cache.has(this.name)) { if (this.global && cache && cache.has(this.name)) {
this.mangled_name = cache.get(this.name); this.mangled_name = cache.get(this.name);
} else if (!this.mangled_name && !this.unmangleable(options)) { } else if (!this.mangled_name && !this.unmangleable(options)) {
var def; var def = this.redefined();
if (def = this.redefined()) { if (def) {
this.mangled_name = def.mangled_name || def.name; this.mangled_name = def.mangled_name || def.name;
} else { } else {
this.mangled_name = next_mangled_name(this.scope, options, this); this.mangled_name = next_mangled_name(this, options);
} }
if (this.global && cache) { if (this.global && cache) {
cache.set(this.name, this.mangled_name); cache.set(this.name, this.mangled_name);
@@ -80,7 +80,15 @@ SymbolDef.prototype = {
} }
}, },
redefined: function() { redefined: function() {
return this.defun && this.defun.variables.get(this.name); var scope = this.defun;
if (!scope) return;
var name = this.name;
var def = scope.variables.get(name)
|| scope instanceof AST_Toplevel && scope.globals.get(name)
|| this.orig[0] instanceof AST_SymbolConst && find_if(function(def) {
return def.name == name;
}, scope.enclosed);
if (def && def !== this) return def.redefined() || def;
}, },
unmangleable: function(options) { unmangleable: function(options) {
return this.global && !options.toplevel return this.global && !options.toplevel
@@ -92,6 +100,8 @@ SymbolDef.prototype = {
}, },
}; };
var unary_side_effects = makePredicate("delete ++ --");
AST_Toplevel.DEFMETHOD("figure_out_scope", function(options) { AST_Toplevel.DEFMETHOD("figure_out_scope", function(options) {
options = defaults(options, { options = defaults(options, {
cache: null, cache: null,
@@ -104,7 +114,7 @@ AST_Toplevel.DEFMETHOD("figure_out_scope", function(options) {
var next_def_id = 0; var next_def_id = 0;
var scope = self.parent_scope = null; var scope = self.parent_scope = null;
var tw = new TreeWalker(function(node, descend) { var tw = new TreeWalker(function(node, descend) {
if (node instanceof AST_Defun) { if (is_defun(node)) {
node.name.walk(tw); node.name.walk(tw);
walk_scope(function() { walk_scope(function() {
node.argnames.forEach(function(argname) { node.argnames.forEach(function(argname) {
@@ -114,13 +124,32 @@ AST_Toplevel.DEFMETHOD("figure_out_scope", function(options) {
}); });
return true; return true;
} }
if (node instanceof AST_BlockScope) { if (node instanceof AST_SwitchBranch) {
walk_scope(descend); node.init_vars(scope);
descend();
return true;
}
if (node instanceof AST_Try) {
walk_scope(function() {
walk_body(node, tw);
});
if (node.bcatch) node.bcatch.walk(tw);
if (node.bfinally) node.bfinally.walk(tw);
return true; return true;
} }
if (node instanceof AST_With) { if (node instanceof AST_With) {
for (var s = scope; s; s = s.parent_scope) s.uses_with = true; var s = scope;
return; do {
s = s.resolve();
if (s.uses_with) break;
s.uses_with = true;
} while (s = s.parent_scope);
walk_scope(descend);
return true;
}
if (node instanceof AST_BlockScope) {
walk_scope(descend);
return true;
} }
if (node instanceof AST_Symbol) { if (node instanceof AST_Symbol) {
node.scope = scope; node.scope = scope;
@@ -131,6 +160,8 @@ AST_Toplevel.DEFMETHOD("figure_out_scope", function(options) {
} }
if (node instanceof AST_SymbolCatch) { if (node instanceof AST_SymbolCatch) {
scope.def_variable(node).defun = defun; scope.def_variable(node).defun = defun;
} else if (node instanceof AST_SymbolConst) {
scope.def_variable(node).defun = defun;
} else if (node instanceof AST_SymbolDefun) { } else if (node instanceof AST_SymbolDefun) {
defun.def_function(node, tw.parent()); defun.def_function(node, tw.parent());
entangle(defun, scope); entangle(defun, scope);
@@ -140,13 +171,15 @@ AST_Toplevel.DEFMETHOD("figure_out_scope", function(options) {
} else if (node instanceof AST_SymbolLambda) { } else if (node instanceof AST_SymbolLambda) {
var def = defun.def_function(node, node.name == "arguments" ? undefined : defun); var def = defun.def_function(node, node.name == "arguments" ? undefined : defun);
if (options.ie8) def.defun = defun.parent_scope.resolve(); if (options.ie8) def.defun = defun.parent_scope.resolve();
} else if (node instanceof AST_SymbolLet) {
scope.def_variable(node);
} else if (node instanceof AST_SymbolVar) { } else if (node instanceof AST_SymbolVar) {
defun.def_variable(node, null); defun.def_variable(node, null);
entangle(defun, scope); entangle(defun, scope);
} }
function walk_scope(descend) { function walk_scope(descend) {
node.init_scope_vars(scope); node.init_vars(scope);
var save_defun = defun; var save_defun = defun;
var save_scope = scope; var save_scope = scope;
if (node instanceof AST_Scope) defun = node; if (node instanceof AST_Scope) defun = node;
@@ -159,7 +192,7 @@ AST_Toplevel.DEFMETHOD("figure_out_scope", function(options) {
function entangle(defun, scope) { function entangle(defun, scope) {
if (defun === scope) return; if (defun === scope) return;
node.mark_enclosed(options); node.mark_enclosed(options);
var def = scope.find_variable(node); var def = scope.find_variable(node.name);
if (node.thedef === def) return; if (node.thedef === def) return;
node.thedef = def; node.thedef = def;
def.orig.push(node); def.orig.push(node);
@@ -173,34 +206,34 @@ AST_Toplevel.DEFMETHOD("figure_out_scope", function(options) {
// pass 2: find back references and eval // pass 2: find back references and eval
self.globals = new Dictionary(); self.globals = new Dictionary();
var in_arg = [];
var tw = new TreeWalker(function(node) { var tw = new TreeWalker(function(node) {
if (node instanceof AST_Catch) {
if (!(node.argname instanceof AST_Destructured)) return;
in_arg.push(node);
node.argname.walk(tw);
in_arg.pop();
walk_body(node, tw);
return true;
}
if (node instanceof AST_Lambda) {
in_arg.push(node);
node.argnames.forEach(function(argname) {
argname.walk(tw);
});
in_arg.pop();
if (node instanceof AST_Arrow && node.value) {
node.value.walk(tw);
} else {
walk_body(node, tw);
}
return true;
}
if (node instanceof AST_LoopControl) { if (node instanceof AST_LoopControl) {
if (node.label) node.label.thedef.references.push(node); if (node.label) node.label.thedef.references.push(node);
return true; return true;
} }
if (node instanceof AST_SymbolRef) { // ensure mangling works if `catch` reuses a scope variable
var name = node.name;
var sym = node.scope.find_variable(name);
if (!sym) {
sym = self.def_global(node);
} else if (sym.scope instanceof AST_Lambda && name == "arguments") {
sym.scope.uses_arguments = true;
}
if (name == "eval") {
var parent = tw.parent();
if (parent.TYPE == "Call" && parent.expression === node) {
for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) {
s.uses_eval = true;
}
} else if (sym.undeclared) {
self.uses_eval = true;
}
}
node.thedef = sym;
node.reference(options);
return true;
}
// ensure mangling works if catch reuses a scope variable
if (node instanceof AST_SymbolCatch) { if (node instanceof AST_SymbolCatch) {
var def = node.definition().redefined(); var def = node.definition().redefined();
if (def) for (var s = node.scope; s; s = s.parent_scope) { if (def) for (var s = node.scope; s; s = s.parent_scope) {
@@ -209,6 +242,61 @@ AST_Toplevel.DEFMETHOD("figure_out_scope", function(options) {
} }
return true; return true;
} }
// ensure compression works if `const` reuses a scope variable
if (node instanceof AST_SymbolConst) {
var redef = node.definition().redefined();
if (redef) redef.const_redefs = true;
return true;
}
if (node instanceof AST_SymbolRef) {
var name = node.name;
var sym = node.scope.find_variable(name);
for (var i = in_arg.length; i > 0 && sym;) {
i = in_arg.lastIndexOf(sym.scope, i - 1);
if (i < 0) break;
var decl = sym.orig[0];
if (decl instanceof AST_SymbolCatch
|| decl instanceof AST_SymbolFunarg
|| decl instanceof AST_SymbolLambda) {
node.in_arg = true;
break;
}
sym = sym.scope.parent_scope.find_variable(name);
}
if (!sym) {
sym = self.def_global(node);
} else if (name == "arguments"
&& sym.orig[0] instanceof AST_SymbolFunarg
&& !(sym.orig[1] instanceof AST_SymbolFunarg)
&& !(sym.scope instanceof AST_Arrow)) {
var parent = tw.parent();
if (parent instanceof AST_Assign && parent.left === node
|| parent instanceof AST_Unary && unary_side_effects[parent.operator]) {
sym.scope.uses_arguments = 3;
} else if (sym.scope.uses_arguments < 2
&& !(parent instanceof AST_PropAccess && parent.expression === node)) {
sym.scope.uses_arguments = 2;
} else if (!sym.scope.uses_arguments) {
sym.scope.uses_arguments = true;
}
}
if (name == "eval") {
var parent = tw.parent();
if (parent.TYPE == "Call" && parent.expression === node) {
var s = node.scope;
do {
s = s.resolve();
if (s.uses_eval) break;
s.uses_eval = true;
} while (s = s.parent_scope);
} else if (sym.undeclared) {
self.uses_eval = true;
}
}
node.thedef = sym;
node.reference(options);
return true;
}
}); });
self.walk(tw); self.walk(tw);
@@ -237,10 +325,13 @@ AST_Toplevel.DEFMETHOD("figure_out_scope", function(options) {
function redefine(node, scope) { function redefine(node, scope) {
var name = node.name; var name = node.name;
var old_def = node.thedef; var old_def = node.thedef;
if (!all(old_def.orig, function(sym) {
return !(sym instanceof AST_SymbolConst || sym instanceof AST_SymbolLet);
})) return;
var new_def = scope.find_variable(name); var new_def = scope.find_variable(name);
if (new_def) { if (new_def) {
var redef; var redef = new_def.redefined();
while (redef = new_def.redefined()) new_def = redef; if (redef) new_def = redef;
} else { } else {
new_def = self.globals.get(name); new_def = self.globals.get(name);
} }
@@ -273,22 +364,30 @@ AST_Toplevel.DEFMETHOD("def_global", function(node) {
} }
}); });
function init_scope_vars(scope, parent) { function init_block_vars(scope, parent) {
scope.cname = -1; // the current index for mangling functions/variables
scope.enclosed = []; // variables from this or outer scope(s) that are referenced from this or inner scopes scope.enclosed = []; // variables from this or outer scope(s) that are referenced from this or inner scopes
scope.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`
scope.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement
scope.parent_scope = parent; // the parent scope (null if this is the top level) scope.parent_scope = parent; // the parent scope (null if this is the top level)
scope.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope) scope.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope)
scope.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions) scope.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions)
if (parent) scope.make_def = parent.make_def; // top-level tracking of SymbolDef instances if (parent) scope.make_def = parent.make_def; // top-level tracking of SymbolDef instances
} }
AST_BlockScope.DEFMETHOD("init_scope_vars", function(parent_scope) { function init_scope_vars(scope, parent) {
init_block_vars(scope, parent);
scope.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`
scope.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement
}
AST_BlockScope.DEFMETHOD("init_vars", function(parent_scope) {
init_block_vars(this, parent_scope);
});
AST_Scope.DEFMETHOD("init_vars", function(parent_scope) {
init_scope_vars(this, parent_scope); init_scope_vars(this, parent_scope);
}); });
AST_Arrow.DEFMETHOD("init_vars", function(parent_scope) {
AST_Lambda.DEFMETHOD("init_scope_vars", function(parent_scope) { init_scope_vars(this, parent_scope);
});
AST_Lambda.DEFMETHOD("init_vars", function(parent_scope) {
init_scope_vars(this, parent_scope); init_scope_vars(this, parent_scope);
this.uses_arguments = false; this.uses_arguments = false;
this.def_variable(new AST_SymbolFunarg({ this.def_variable(new AST_SymbolFunarg({
@@ -318,14 +417,13 @@ AST_Symbol.DEFMETHOD("reference", function(options) {
}); });
AST_BlockScope.DEFMETHOD("find_variable", function(name) { AST_BlockScope.DEFMETHOD("find_variable", function(name) {
if (name instanceof AST_Symbol) name = name.name;
return this.variables.get(name) return this.variables.get(name)
|| (this.parent_scope && this.parent_scope.find_variable(name)); || this.parent_scope && this.parent_scope.find_variable(name);
}); });
AST_BlockScope.DEFMETHOD("def_function", function(symbol, init) { AST_BlockScope.DEFMETHOD("def_function", function(symbol, init) {
var def = this.def_variable(symbol, init); var def = this.def_variable(symbol, init);
if (!def.init || def.init instanceof AST_Defun) def.init = init; if (!def.init || is_defun(def.init)) def.init = init;
this.functions.set(symbol.name, def); this.functions.set(symbol.name, def);
return def; return def;
}); });
@@ -334,7 +432,7 @@ AST_BlockScope.DEFMETHOD("def_variable", function(symbol, init) {
var def = this.variables.get(symbol.name); var def = this.variables.get(symbol.name);
if (def) { if (def) {
def.orig.push(symbol); def.orig.push(symbol);
if (def.init instanceof AST_Function) def.init = init; if (is_function(def.init)) def.init = init;
} else { } else {
def = this.make_def(symbol, init); def = this.make_def(symbol, init);
this.variables.set(symbol.name, def); this.variables.set(symbol.name, def);
@@ -346,8 +444,9 @@ AST_BlockScope.DEFMETHOD("def_variable", function(symbol, init) {
function names_in_use(scope, options) { function names_in_use(scope, options) {
var names = scope.names_in_use; var names = scope.names_in_use;
if (!names) { if (!names) {
scope.names_in_use = names = Object.create(null); scope.cname = -1;
scope.cname_holes = []; scope.cname_holes = [];
scope.names_in_use = names = Object.create(null);
var cache = options.cache && options.cache.props; var cache = options.cache && options.cache.props;
scope.enclosed.forEach(function(def) { scope.enclosed.forEach(function(def) {
if (def.unmangleable(options)) names[def.name] = true; if (def.unmangleable(options)) names[def.name] = true;
@@ -359,7 +458,8 @@ function names_in_use(scope, options) {
return names; return names;
} }
function next_mangled_name(scope, options, def) { function next_mangled_name(def, options) {
var scope = def.scope;
var in_use = names_in_use(scope, options); var in_use = names_in_use(scope, options);
var holes = scope.cname_holes; var holes = scope.cname_holes;
var names = Object.create(null); var names = Object.create(null);
@@ -412,6 +512,7 @@ function _default_mangler_options(options) {
keep_fnames : false, keep_fnames : false,
reserved : [], reserved : [],
toplevel : false, toplevel : false,
webkit : false,
}); });
if (!Array.isArray(options.reserved)) options.reserved = []; if (!Array.isArray(options.reserved)) options.reserved = [];
// Never mangle arguments // Never mangle arguments
@@ -445,7 +546,26 @@ AST_Toplevel.DEFMETHOD("mangle_names", function(options) {
lname = save_nesting; lname = save_nesting;
return true; return true;
} }
if (node instanceof AST_Scope) { if (node instanceof AST_BlockScope) {
if (options.webkit && node instanceof AST_IterationStatement && node.init instanceof AST_Let) {
node.init.definitions.forEach(function(defn) {
defn.name.match_symbol(function(sym) {
if (!(sym instanceof AST_SymbolLet)) return;
var def = sym.definition();
var scope = sym.scope.parent_scope;
var redef = scope.def_variable(sym);
sym.thedef = def;
scope.to_mangle.push(redef);
def.redefined = function() {
return redef;
};
});
}, true);
}
node.to_mangle = [];
node.variables.each(function(def) {
if (!defer_redef(def)) node.to_mangle.push(def);
});
descend(); descend();
if (options.cache && node instanceof AST_Toplevel) { if (options.cache && node instanceof AST_Toplevel) {
node.globals.each(mangle); node.globals.each(mangle);
@@ -455,9 +575,7 @@ AST_Toplevel.DEFMETHOD("mangle_names", function(options) {
sym.scope = node; sym.scope = node;
sym.reference(options); sym.reference(options);
} }
node.variables.each(function(def) { node.to_mangle.forEach(mangle);
if (!defer_redef(def)) mangle(def);
});
return true; return true;
} }
if (node instanceof AST_Label) { if (node instanceof AST_Label) {
@@ -468,13 +586,6 @@ AST_Toplevel.DEFMETHOD("mangle_names", function(options) {
node.mangled_name = name; node.mangled_name = name;
return true; return true;
} }
if (!options.ie8 && node instanceof AST_Catch) {
var def = node.argname.definition();
var redef = defer_redef(def, node.argname);
descend();
if (!redef) mangle(def);
return true;
}
}); });
this.walk(tw); this.walk(tw);
redefined.forEach(mangle); redefined.forEach(mangle);
@@ -484,12 +595,19 @@ AST_Toplevel.DEFMETHOD("mangle_names", function(options) {
def.mangle(options); def.mangle(options);
} }
function defer_redef(def, node) { function defer_redef(def) {
var sym = def.orig[0];
var redef = def.redefined(); var redef = def.redefined();
if (!redef) return false; if (!redef) {
if (!(sym instanceof AST_SymbolConst)) return false;
var scope = def.scope.resolve();
if (def.scope === scope) return false;
redef = scope.def_variable(sym);
scope.to_mangle.push(redef);
}
redefined.push(def); redefined.push(def);
def.references.forEach(reference); def.references.forEach(reference);
if (node) reference(node); if (sym instanceof AST_SymbolCatch || sym instanceof AST_SymbolConst) reference(sym);
return true; return true;
function reference(sym) { function reference(sym) {

View File

@@ -116,7 +116,7 @@ TreeTransformer.prototype = new TreeWalker;
if (self.bfinally) self.bfinally = self.bfinally.transform(tw); if (self.bfinally) self.bfinally = self.bfinally.transform(tw);
}); });
DEF(AST_Catch, function(self, tw) { DEF(AST_Catch, function(self, tw) {
self.argname = self.argname.transform(tw); if (self.argname) self.argname = self.argname.transform(tw);
self.body = do_list(self.body, tw); self.body = do_list(self.body, tw);
}); });
DEF(AST_Definitions, function(self, tw) { DEF(AST_Definitions, function(self, tw) {
@@ -131,6 +131,14 @@ TreeTransformer.prototype = new TreeWalker;
self.argnames = do_list(self.argnames, tw); self.argnames = do_list(self.argnames, tw);
self.body = do_list(self.body, tw); self.body = do_list(self.body, tw);
}); });
DEF(AST_Arrow, function(self, tw) {
self.argnames = do_list(self.argnames, tw);
if (self.value) {
self.value = self.value.transform(tw);
} else {
self.body = do_list(self.body, tw);
}
});
DEF(AST_Call, function(self, tw) { DEF(AST_Call, function(self, tw) {
self.expression = self.expression.transform(tw); self.expression = self.expression.transform(tw);
self.args = do_list(self.args, tw); self.args = do_list(self.args, tw);
@@ -138,6 +146,9 @@ TreeTransformer.prototype = new TreeWalker;
DEF(AST_Sequence, function(self, tw) { DEF(AST_Sequence, function(self, tw) {
self.expressions = do_list(self.expressions, tw); self.expressions = do_list(self.expressions, tw);
}); });
DEF(AST_Await, function(self, tw) {
self.expression = self.expression.transform(tw);
});
DEF(AST_Dot, function(self, tw) { DEF(AST_Dot, function(self, tw) {
self.expression = self.expression.transform(tw); self.expression = self.expression.transform(tw);
}); });
@@ -145,6 +156,9 @@ TreeTransformer.prototype = new TreeWalker;
self.expression = self.expression.transform(tw); self.expression = self.expression.transform(tw);
self.property = self.property.transform(tw); self.property = self.property.transform(tw);
}); });
DEF(AST_Spread, function(self, tw) {
self.expression = self.expression.transform(tw);
});
DEF(AST_Unary, function(self, tw) { DEF(AST_Unary, function(self, tw) {
self.expression = self.expression.transform(tw); self.expression = self.expression.transform(tw);
}); });
@@ -160,10 +174,21 @@ TreeTransformer.prototype = new TreeWalker;
DEF(AST_Array, function(self, tw) { DEF(AST_Array, function(self, tw) {
self.elements = do_list(self.elements, tw); self.elements = do_list(self.elements, tw);
}); });
DEF(AST_DestructuredArray, function(self, tw) {
self.elements = do_list(self.elements, tw);
});
DEF(AST_DestructuredKeyVal, function(self, tw) {
if (self.key instanceof AST_Node) self.key = self.key.transform(tw);
self.value = self.value.transform(tw);
});
DEF(AST_DestructuredObject, function(self, tw) {
self.properties = do_list(self.properties, tw);
});
DEF(AST_Object, function(self, tw) { DEF(AST_Object, function(self, tw) {
self.properties = do_list(self.properties, tw); self.properties = do_list(self.properties, tw);
}); });
DEF(AST_ObjectProperty, function(self, tw) { DEF(AST_ObjectProperty, function(self, tw) {
if (self.key instanceof AST_Node) self.key = self.key.transform(tw);
self.value = self.value.transform(tw); self.value = self.value.transform(tw);
}); });
})(function(node, descend) { })(function(node, descend) {

View File

@@ -143,8 +143,9 @@ function push_uniq(array, el) {
} }
function string_template(text, props) { function string_template(text, props) {
return text.replace(/\{(.+?)\}/g, function(str, p) { return text.replace(/\{([^}]+)\}/g, function(str, p) {
return props && props[p]; var value = props[p];
return value instanceof AST_Node ? value.print_to_string() : value;
}); });
} }
@@ -237,13 +238,15 @@ function HOP(obj, prop) {
// return true if the node at the top of the stack (that means the // return true if the node at the top of the stack (that means the
// innermost node in the current output) is lexically the first in // innermost node in the current output) is lexically the first in
// a statement. // a statement.
function first_in_statement(stack) { function first_in_statement(stack, arrow) {
var node = stack.parent(-1); var node = stack.parent(-1);
for (var i = 0, p; p = stack.parent(i++); node = p) { for (var i = 0, p; p = stack.parent(i++); node = p) {
if (p.TYPE == "Call") { if (p instanceof AST_Arrow) {
if (p.expression === node) continue; return arrow && p.value === node;
} else if (p instanceof AST_Binary) { } else if (p instanceof AST_Binary) {
if (p.left === node) continue; if (p.left === node) continue;
} else if (p.TYPE == "Call") {
if (p.expression === node) continue;
} else if (p instanceof AST_Conditional) { } else if (p instanceof AST_Conditional) {
if (p.condition === node) continue; if (p.condition === node) continue;
} else if (p instanceof AST_PropAccess) { } else if (p instanceof AST_PropAccess) {

View File

@@ -3,7 +3,7 @@
"description": "JavaScript parser, mangler/compressor and beautifier toolkit", "description": "JavaScript parser, mangler/compressor and beautifier toolkit",
"author": "Mihai Bazon <mihai.bazon@gmail.com> (http://lisperator.net/)", "author": "Mihai Bazon <mihai.bazon@gmail.com> (http://lisperator.net/)",
"license": "BSD-2-Clause", "license": "BSD-2-Clause",
"version": "3.11.1", "version": "3.12.3",
"engines": { "engines": {
"node": ">=0.8.0" "node": ">=0.8.0"
}, },

View File

@@ -63,7 +63,6 @@ function make_code(ast, options) {
function parse_test(file) { function parse_test(file) {
var script = fs.readFileSync(file, "utf8"); var script = fs.readFileSync(file, "utf8");
// TODO try/catch can be removed after fixing https://github.com/mishoo/UglifyJS/issues/348
try { try {
var ast = U.parse(script, { var ast = U.parse(script, {
filename: file filename: file
@@ -315,6 +314,7 @@ function test_case(test) {
if (test.mangle.properties) U.mangle_properties(output, test.mangle.properties); if (test.mangle.properties) U.mangle_properties(output, test.mangle.properties);
} }
var output_code = make_code(output, output_options); var output_code = make_code(output, output_options);
U.AST_Node.log_function();
if (expect != output_code) { if (expect != output_code) {
log([ log([
"!!! failed", "!!! failed",
@@ -386,7 +386,7 @@ function test_case(test) {
mangle: test.mangle mangle: test.mangle
}); });
var actual = stdout[toplevel ? 1 : 0]; var actual = stdout[toplevel ? 1 : 0];
if (test.expect_stdout === true) { if (test.expect_stdout === true || test.expect_stdout instanceof Error && test.expect_stdout.name === actual.name) {
test.expect_stdout = actual; test.expect_stdout = actual;
} }
if (!sandbox.same_stdout(test.expect_stdout, actual)) { if (!sandbox.same_stdout(test.expect_stdout, actual)) {

View File

@@ -783,3 +783,182 @@ issue_3420_7: {
} }
expect_stdout: "true" expect_stdout: "true"
} }
issue_4200: {
options = {
arguments: true,
keep_fargs: false,
}
input: {
var o = {
get p() {
return arguments[0];
},
};
console.log(o.p);
}
expect: {
var o = {
get p() {
return arguments[0];
},
};
console.log(o.p);
}
expect_stdout: "undefined"
}
issue_4291_1: {
options = {
arguments: true,
keep_fargs: "strict",
}
input: {
console.log(function() {
arguments[0] = "PASS";
return arguments;
}()[0]);
}
expect: {
console.log(function() {
arguments[0] = "PASS";
return arguments;
}()[0]);
}
expect_stdout: "PASS"
}
issue_4291_2: {
options = {
arguments: true,
keep_fargs: "strict",
}
input: {
var a = function() {
if (arguments[0])
arguments[1] = "PASS";
return arguments;
}(42);
console.log(a[1], a[0], a.length);
}
expect: {
var a = function(argument_0) {
if (argument_0)
arguments[1] = "PASS";
return arguments;
}(42);
console.log(a[1], a[0], a.length);
}
expect_stdout: "PASS 42 1"
}
issue_4397: {
options = {
arguments: true,
keep_fargs: "strict",
}
input: {
console.log(typeof function() {
arguments += 0;
return arguments[0];
}());
}
expect: {
console.log(typeof function() {
arguments += 0;
return arguments[0];
}());
}
expect_stdout: "string"
}
issue_4410_1: {
options = {
arguments: true,
conditionals: true,
evaluate: true,
reduce_vars: true,
}
input: {
(function(a) {
console.log(arguments[0] === (a = 0) ? "FAIL" : "PASS");
})(1);
}
expect: {
(function(a) {
console.log(a === (a = 0) ? "FAIL" : "PASS");
})(1);
}
expect_stdout: "PASS"
}
issue_4410_2: {
options = {
arguments: true,
conditionals: true,
evaluate: true,
reduce_vars: true,
}
input: {
(function f(a) {
console.log(arguments[0] === (a = 0) ? "FAIL" : "PASS");
})(1);
}
expect: {
(function f(a) {
console.log(arguments[0] === (a = 0) ? "FAIL" : "PASS");
})(1);
}
expect_stdout: "PASS"
}
issue_4410_3: {
options = {
arguments: true,
}
input: {
var a = 1;
(function f(b) {
a-- && f();
for (var c = 2; c--;)
switch (arguments[0]) {
case b = 42:
case 42:
console.log("PASS");
}
})(null);
}
expect: {
var a = 1;
(function f(b) {
a-- && f();
for (var c = 2; c--;)
switch (arguments[0]) {
case b = 42:
case 42:
console.log("PASS");
}
})(null);
}
expect_stdout: "PASS"
}
issue_4432: {
options = {
arguments: true,
reduce_vars: true,
}
input: {
console.log(function(a) {
for (a in { FAIL: 42 });
return arguments[0];
}() || "PASS");
}
expect: {
console.log(function(a) {
for (a in { FAIL: 42 });
return arguments[0];
}() || "PASS");
}
expect_stdout: "PASS"
}

589
test/compress/arrows.js Normal file
View File

@@ -0,0 +1,589 @@
no_funarg: {
input: {
(() => console.log(42))();
}
expect_exact: "(()=>console.log(42))();"
expect_stdout: "42"
node_version: ">=4"
}
single_funarg: {
input: {
(a => console.log(a))(42);
}
expect_exact: "(a=>console.log(a))(42);"
expect_stdout: "42"
node_version: ">=4"
}
multiple_funargs: {
input: {
((a, b) => console.log(a, b))("foo", "bar");
}
expect_exact: '((a,b)=>console.log(a,b))("foo","bar");'
expect_stdout: "foo bar"
node_version: ">=4"
}
destructured_funarg: {
input: {
(([ a, b, c ]) => console.log(a, b, c))("foo");
}
expect_exact: '(([a,b,c])=>console.log(a,b,c))("foo");'
expect_stdout: "f o o"
node_version: ">=6"
}
await_parenthesis: {
input: {
async function f() {
await (a => a);
}
}
expect_exact: "async function f(){await(a=>a)}"
}
for_parenthesis_init: {
input: {
for (a => (a in a); console.log(42););
}
expect_exact: "for((a=>a in a);console.log(42););"
expect_stdout: "42"
node_version: ">=4"
}
for_parenthesis_condition: {
input: {
for (console.log(42); a => (a in a);)
break;
}
expect_exact: "for(console.log(42);a=>a in a;)break;"
expect_stdout: "42"
node_version: ">=4"
}
for_parenthesis_step: {
input: {
for (; console.log(42); a => (a in a));
}
expect_exact: "for(;console.log(42);a=>a in a);"
expect_stdout: "42"
node_version: ">=4"
}
for_assign_parenthesis_init: {
input: {
for (f = a => (a in a); console.log(42););
}
expect_exact: "for((f=a=>a in a);console.log(42););"
expect_stdout: "42"
node_version: ">=4"
}
for_assign_parenthesis_condition: {
input: {
for (console.log(42); f = a => (a in a);)
break;
}
expect_exact: "for(console.log(42);f=a=>a in a;)break;"
expect_stdout: "42"
node_version: ">=4"
}
for_assign_parenthesis_step: {
input: {
for (; console.log(42); f = a => (a in a));
}
expect_exact: "for(;console.log(42);f=a=>a in a);"
expect_stdout: "42"
node_version: ">=4"
}
for_declaration_parenthesis_init: {
input: {
for (var f = a => (a in a); console.log(42););
}
expect_exact: "for(var f=(a=>a in a);console.log(42););"
expect_stdout: "42"
node_version: ">=4"
}
for_statement_parenthesis_init: {
input: {
for (a => {
a in a;
}; console.log(42););
}
expect_exact: "for(a=>{a in a};console.log(42););"
expect_stdout: "42"
node_version: ">=4"
}
body_call: {
input: {
(() => {
console.log("foo");
console.log("bar");
})();
}
expect_exact: '(()=>{console.log("foo");console.log("bar")})();'
expect_stdout: [
"foo",
"bar",
]
node_version: ">=4"
}
body_conditional: {
input: {
console.log((a => {}) ? "PASS" : "FAIL");
}
expect_exact: 'console.log((a=>{})?"PASS":"FAIL");'
expect_stdout: "PASS"
node_version: ">=4"
}
destructured_object_value: {
input: {
console.log((a => ({} = a))(42));
}
expect_exact: "console.log((a=>({}=a))(42));"
expect_stdout: "42"
node_version: ">=6"
}
function_value: {
input: {
console.log((a => function() {
return a;
})(42)());
}
expect_exact: "console.log((a=>function(){return a})(42)());"
expect_stdout: "42"
node_version: ">=4"
}
in_value: {
input: {
console.log((a => a in {
foo: 42,
})("foo"));
}
expect_exact: 'console.log((a=>a in{foo:42})("foo"));'
expect_stdout: "true"
node_version: ">=4"
}
object_value: {
input: {
console.log((() => ({
4: 2,
}))()[4]);
}
expect_exact: "console.log((()=>({4:2}))()[4]);"
expect_stdout: "2"
node_version: ">=4"
}
object_first_in_value: {
input: {
console.log((a => ({
p: a,
}.p ? "FAIL" : "PASS"))());
}
expect_exact: 'console.log((a=>({p:a}).p?"FAIL":"PASS")());'
expect_stdout: "PASS"
node_version: ">=4"
}
sequence_value: {
input: {
console.log((a => (console.log("foo"), a))("bar"));
}
expect_exact: 'console.log((a=>(console.log("foo"),a))("bar"));'
expect_stdout: [
"foo",
"bar",
]
node_version: ">=4"
}
side_effects_value: {
options = {
side_effects: true,
}
input: {
console.log((a => function() {
return a;
})(42)());
}
expect: {
console.log((a => function() {
return a;
})(42)());
}
expect_stdout: "42"
node_version: ">=4"
}
arrow_property: {
input: {
console.log((a => 42).prototype);
}
expect_exact: "console.log((a=>42).prototype);"
expect_stdout: "undefined"
node_version: ">=4"
}
assign_arrow: {
input: {
var f = a => a;
console.log(f(42));
}
expect_exact: "var f=a=>a;console.log(f(42));"
expect_stdout: "42"
node_version: ">=4"
}
binary_arrow: {
input: {
console.log(4 || (() => 2));
}
expect_exact: "console.log(4||(()=>2));"
expect_stdout: "4"
node_version: ">=4"
}
unary_arrow: {
input: {
console.log(+(() => 42));
}
expect_exact: "console.log(+(()=>42));"
expect_stdout: "NaN"
node_version: ">=4"
}
trailing_comma: {
input: {
((a,) => console.log(a))(42);
}
expect_exact: "(a=>console.log(a))(42);"
expect_stdout: "42"
node_version: ">=4"
}
drop_arguments: {
options = {
arguments: true,
keep_fargs: false,
}
input: {
console.log(function() {
return () => arguments[0];
}("PASS")("FAIL"));
}
expect: {
console.log(function(argument_0) {
return () => argument_0;
}("PASS")("FAIL"));
}
expect_stdout: "PASS"
node_version: ">=4"
}
funarg_arguments: {
options = {
inline: true,
}
input: {
console.log((arguments => arguments)(42));
}
expect: {
console.log(42);
}
expect_stdout: "42"
node_version: ">=4"
}
inline_arguments: {
options = {
inline: true,
}
input: {
console.log(function() {
return () => arguments[0];
}("PASS")("FAIL"));
}
expect: {
console.log(function() {
return () => arguments[0];
}("PASS")("FAIL"));
}
expect_stdout: "PASS"
node_version: ">=4"
}
var_arguments: {
options = {
inline: true,
properties: true,
reduce_vars: true,
side_effects: true,
unused: true,
}
input: {
console.log(function() {
return () => {
var arguments = [ "PASS" ];
return arguments;
};
}("FAIL 1")("FAIL 2")[0]);
}
expect: {
console.log("PASS");
}
expect_stdout: "PASS"
node_version: ">=4"
}
negate: {
options = {
conditionals: true,
}
input: {
if (!console ? 0 : () => 1)
console.log("PASS");
}
expect: {
(console ? () => 1 : 0) && console.log("PASS");
}
expect_stdout: "PASS"
node_version: ">=4"
}
inline_this: {
options = {
inline: true,
}
input: {
var o = {
p: function() {
return function() {
return () => this.q;
}();
},
q: "FAIL",
};
q = "PASS";
console.log(o.p()());
}
expect: {
var o = {
p: function() {
return function() {
return () => this.q;
}();
},
q: "FAIL",
};
q = "PASS";
console.log(o.p()());
}
expect_stdout: "PASS"
node_version: ">=4"
}
trim_body: {
options = {
arrows: true,
if_return: true,
side_effects: true,
}
input: {
var f = a => {
return a;
};
var g = b => void b;
console.log(f("PASS"), g("FAIL"));
}
expect: {
var f = a => a;
var g = b => {};
console.log(f("PASS"), g("FAIL"));
}
expect_stdout: "PASS undefined"
node_version: ">=4"
}
collapse_value: {
options = {
arrows: true,
collapse_vars: true,
keep_fargs: "strict",
unused: true,
}
input: {
var a = 42;
console.log((b => Math.floor(b))(a));
}
expect: {
var a = 42;
console.log((() => Math.floor(a))());
}
expect_stdout: "42"
node_version: ">=4"
}
reduce_iife_1: {
options = {
evaluate: true,
keep_fargs: "strict",
reduce_vars: true,
unused: true,
}
input: {
(a => console.log(a + a))(21);
}
expect: {
(() => console.log(42))();
}
expect_stdout: "42"
node_version: ">=4"
}
reduce_iife_2: {
options = {
evaluate: true,
reduce_vars: true,
toplevel: true,
unused: true,
}
input: {
var a = 21;
(() => console.log(a + a))();
}
expect: {
(() => console.log(42))();
}
expect_stdout: "42"
node_version: ">=4"
}
reduce_iife_3: {
options = {
evaluate: true,
reduce_vars: true,
side_effects: true,
toplevel: true,
unused: true,
}
input: {
var a = "foo";
(() => {
console.log(a);
console.log(a);
})();
a = "bar";
}
expect: {
(() => {
console.log("foo");
console.log("foo");
})();
}
expect_stdout: [
"foo",
"foo",
]
node_version: ">=4"
}
single_use_recursive: {
options = {
reduce_vars: true,
toplevel: true,
unused: true,
}
input: {
function f() {
return (() => f)();
}
console.log(typeof f());
}
expect: {
console.log(typeof function f() {
return (() => f)();
}());
}
expect_stdout: "function"
node_version: ">=4"
}
issue_4388: {
options = {
inline: true,
toplevel: true,
}
input: {
(arguments => console.log(arguments && arguments))();
}
expect: {
(arguments => console.log(arguments && arguments))();
}
expect_stdout: "undefined"
node_version: ">=4"
}
issue_4390: {
options = {
collapse_vars: true,
}
input: {
function log() {
console.log.apply(console, arguments);
}
var a = 42, b = "FAIL";
b = "PASS";
(c => log(b, c))(a);
log(b);
}
expect: {
function log() {
console.log.apply(console, arguments);
}
var a = 42, b = "FAIL";
b = "PASS";
(c => log(b, c))(a);
log(b);
}
expect_stdout: [
"PASS 42",
"PASS",
]
node_version: ">=4"
}
issue_4401: {
options = {
merge_vars: true,
}
input: {
(function() {
var a = (b => b(a))(console.log || a);
var c = console.log;
c && c(typeof b);
})();
}
expect: {
(function() {
var a = (b => b(a))(console.log || a);
var c = console.log;
c && c(typeof b);
})();
}
expect_stdout: [
"undefined",
"undefined",
]
node_version: ">=4"
}

View File

@@ -1,35 +0,0 @@
ascii_only_true: {
options = {}
beautify = {
ascii_only : true,
ie8 : false,
beautify : false,
}
input: {
function f() {
return "\x000\x001\x007\x008\x00" +
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" +
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" +
"\x20\x21\x22\x23 ... \x7d\x7e\x7f\x80\x81 ... \xfe\xff\u0fff\uffff";
}
}
expect_exact: 'function f(){return"\\x000\\x001\\x007\\x008\\0"+"\\0\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\b\\t\\n\\v\\f\\r\\x0e\\x0f"+"\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f"+\' !"# ... }~\\x7f\\x80\\x81 ... \\xfe\\xff\\u0fff\\uffff\'}'
}
ascii_only_false: {
options = {}
beautify = {
ascii_only : false,
ie8 : false,
beautify : false,
}
input: {
function f() {
return "\x000\x001\x007\x008\x00" +
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" +
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" +
"\x20\x21\x22\x23 ... \x7d\x7e\x7f\x80\x81 ... \xfe\xff\u0fff\uffff";
}
}
expect_exact: 'function f(){return"\\x000\\x001\\x007\\x008\\0"+"\\0\x01\x02\x03\x04\x05\x06\x07\\b\\t\\n\\v\\f\\r\x0e\x0f"+"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"+\' !"# ... }~\x7f\x80\x81 ... \xfe\xff\u0fff\uffff\'}'
}

View File

@@ -76,9 +76,8 @@ asm_mixed: {
start = start | 0; start = start | 0;
end = end | 0; end = end | 0;
var sum = 0.0, p = 0, q = 0; var sum = 0.0, p = 0, q = 0;
for (p = start << 3, q = end << 3; (p | 0) < (q | 0); p = p + 8 | 0) { for (p = start << 3, q = end << 3; (p | 0) < (q | 0); p = p + 8 | 0)
sum = sum + +log(values[p >> 3]); sum = sum + +log(values[p >> 3]);
}
return +sum; return +sum;
} }
function geometricMean(start, end) { function geometricMean(start, end) {
@@ -91,7 +90,8 @@ asm_mixed: {
function no_asm_GeometricMean(stdlib, foreign, buffer) { function no_asm_GeometricMean(stdlib, foreign, buffer) {
function logSum(start, end) { function logSum(start, end) {
start |= 0, end |= 0; start |= 0, end |= 0;
for (var sum = 0, p = 0, q = 0, p = start << 3, q = end << 3; (0 | p) < (0 | q); p = p + 8 | 0) sum += +log(values[p >> 3]); for (var sum = 0, p = 0, q = 0, p = start << 3, q = end << 3; (0 | p) < (0 | q); p = p + 8 | 0)
sum += +log(values[p >> 3]);
return +sum; return +sum;
} }
function geometricMean(start, end) { function geometricMean(start, end) {

642
test/compress/async.js Normal file
View File

@@ -0,0 +1,642 @@
await_await: {
input: {
(async function() {
console.log("PASS");
await await 42;
})();
}
expect: {
(async function() {
console.log("PASS");
await await 42;
})();
}
expect_stdout: "PASS"
node_version: ">=8"
}
defun_name: {
input: {
async function await() {
console.log("PASS");
}
await();
}
expect: {
async function await() {
console.log("PASS");
}
await();
}
expect_stdout: "PASS"
node_version: ">=8"
}
nested_await: {
input: {
(async function() {
console.log(function(await) {
return await;
}("PASS"));
})();
}
expect: {
(async function() {
console.log(function(await) {
return await;
}("PASS"));
})();
}
expect_stdout: "PASS"
node_version: ">=8"
}
reduce_single_use_defun: {
options = {
reduce_vars: true,
toplevel: true,
unused: true,
}
input: {
async function f(a) {
console.log(a);
}
f("PASS");
}
expect: {
(async function(a) {
console.log(a);
})("PASS");
}
expect_stdout: "PASS"
node_version: ">=8"
}
dont_inline: {
options = {
inline: true,
}
input: {
(async function() {
A;
})().catch(function() {});
console.log("PASS");
}
expect: {
(async function() {
A;
})().catch(function() {});
console.log("PASS");
}
expect_stdout: "PASS"
node_version: ">=8"
}
evaluate: {
options = {
evaluate: true,
reduce_vars: true,
toplevel: true,
unused: true,
}
input: {
var a = async function() {}();
console.log(typeof a);
}
expect: {
var a = async function() {}();
console.log(typeof a);
}
expect_stdout: "object"
node_version: ">=8"
}
negate: {
options = {
side_effects: true,
}
input: {
console && async function() {} && console.log("PASS");
}
expect: {
console && async function() {} && console.log("PASS");
}
expect_stdout: "PASS"
node_version: ">=8"
}
negate_iife: {
options = {
negate_iife: true,
}
input: {
(async function() {
console.log("PASS");
})();
}
expect: {
!async function() {
console.log("PASS");
}();
}
expect_stdout: "PASS"
node_version: ">=8"
}
object_function: {
options = {
properties: true,
side_effects: true,
}
input: {
({
async f() {
console.log("PASS");
},
}).f();
}
expect: {
(async function() {
console.log("PASS");
})();
}
expect_stdout: "PASS"
node_version: ">=8"
}
collapse_vars_1: {
options = {
collapse_vars: true,
}
input: {
var a = "FAIL";
(async function() {
a = "PASS";
await 42;
return "PASS";
})();
console.log(a);
}
expect: {
var a = "FAIL";
(async function() {
a = "PASS";
await 42;
return "PASS";
})();
console.log(a);
}
expect_stdout: "PASS"
node_version: ">=8"
}
collapse_vars_2: {
options = {
collapse_vars: true,
}
input: {
var a = "FAIL";
(async function() {
await (a = "PASS");
return "PASS";
})();
console.log(a);
}
expect: {
var a = "FAIL";
(async function() {
await (a = "PASS");
return "PASS";
})();
console.log(a);
}
expect_stdout: "PASS"
node_version: ">=8"
}
collapse_vars_3: {
options = {
collapse_vars: true,
}
input: {
var a = "FAIL";
(async function() {
await (a = "PASS", 42);
return "PASS";
})();
console.log(a);
}
expect: {
var a = "FAIL";
(async function() {
await (a = "PASS", 42);
return "PASS";
})();
console.log(a);
}
expect_stdout: "PASS"
node_version: ">=8"
}
issue_4335_1: {
options = {
inline: true,
}
input: {
var await = "PASS";
(async function() {
console.log(function() {
return await;
}());
})();
}
expect: {
var await = "PASS";
(async function() {
console.log(function() {
return await;
}());
})();
}
expect_stdout: "PASS"
node_version: ">=8"
}
issue_4335_2: {
options = {
inline: true,
}
input: {
(async function() {
console.log(function() {
function await() {}
return "PASS";
}());
})();
}
expect: {
(async function() {
console.log(function() {
function await() {}
return "PASS";
}());
})();
}
expect_stdout: "PASS"
node_version: ">=8"
}
issue_4337: {
options = {
reduce_vars: true,
unused: true,
}
input: {
(function(a) {
a();
})(async function() {
console.log("PASS");
});
}
expect: {
(function(a) {
(async function() {
console.log("PASS");
})();
})();
}
expect_stdout: "PASS"
node_version: ">=8"
}
issue_4340: {
options = {
evaluate: true,
reduce_vars: true,
}
input: {
(async function a(a) {
console.log(a || "PASS");
})();
}
expect: {
(async function a(a) {
console.log(a || "PASS");
})();
}
expect_stdout: "PASS"
node_version: ">=8"
}
call_expression: {
input: {
console.log(typeof async function(log) {
(await log)("FAIL");
}(console.log).then);
}
expect_exact: 'console.log(typeof async function(log){(await log)("FAIL")}(console.log).then);'
expect_stdout: "function"
node_version: ">=8"
}
property_access_expression: {
input: {
console.log(typeof async function(con) {
(await con).log("FAIL");
}(console).then);
}
expect_exact: 'console.log(typeof async function(con){(await con).log("FAIL")}(console).then);'
expect_stdout: "function"
node_version: ">=8"
}
reduce_iife_1: {
options = {
evaluate: true,
keep_fargs: "strict",
reduce_vars: true,
unused: true,
}
input: {
(async function(a) {
console.log(a + a);
})(21);
}
expect: {
(async function() {
console.log(42);
})();
}
expect_stdout: "42"
node_version: ">=8"
}
reduce_iife_2: {
options = {
evaluate: true,
reduce_vars: true,
toplevel: true,
unused: true,
}
input: {
var a = 21;
(async function() {
console.log(a + a);
})();
}
expect: {
(async function() {
console.log(42);
})();
}
expect_stdout: "42"
node_version: ">=8"
}
reduce_iife_3: {
options = {
evaluate: true,
reduce_vars: true,
side_effects: true,
toplevel: true,
unused: true,
}
input: {
var a = "foo";
(async function() {
console.log(a);
console.log(await a);
})();
a = "bar";
}
expect: {
var a = "foo";
(async function() {
console.log(a);
console.log(await a);
})();
a = "bar";
}
expect_stdout: "foo"
node_version: ">=8"
}
issue_4347_1: {
options = {
evaluate: true,
reduce_vars: true,
toplevel: true,
unused: true,
}
input: {
var a = "foo";
f();
a = "bar";
f();
async function f() {
console.log(a);
}
}
expect: {
var a = "foo";
f();
a = "bar";
f();
async function f() {
console.log(a);
}
}
expect_stdout: [
"foo",
"bar",
]
node_version: ">=8"
}
issue_4347_2: {
options = {
evaluate: true,
reduce_vars: true,
toplevel: true,
unused: true,
}
input: {
var a = "PASS";
(async function() {
throw 42;
a = "FAIL";
})();
console.log(a);
}
expect: {
var a = "PASS";
(async function() {
throw 42;
a = "FAIL";
})();
console.log(a);
}
expect_stdout: "PASS"
node_version: ">=8"
}
issue_4349_1: {
input: {
console.log(typeof async function() {
await /abc/;
}().then);
}
expect_exact: "console.log(typeof async function(){await/abc/}().then);"
expect_stdout: "function"
node_version: ">=8"
}
issue_4349_2: {
options = {
collapse_vars: true,
unused: true,
}
input: {
console.log(typeof async function() {
(function(a) {
this[a];
}(await 0));
}().then);
}
expect: {
console.log(typeof async function() {
(function(a) {
this[a];
}(await 0));
}().then);
}
expect_stdout: "function"
node_version: ">=8"
}
issue_4349_3: {
options = {
collapse_vars: true,
unused: true,
}
input: {
console.log(typeof function(await) {
return async function(a) {
this[a];
}(await);
}(this).then);
}
expect: {
console.log(typeof function(await) {
return async function(a) {
this[a];
}(await);
}(this).then);
}
expect_stdout: "function"
node_version: ">=8"
}
issue_4359: {
options = {
collapse_vars: true,
unused: true,
}
input: {
try {
(async function(a) {
return a;
})(A);
} catch (e) {
console.log("PASS");
}
}
expect: {
try {
(async function(a) {
return a;
})(A);
} catch (e) {
console.log("PASS");
}
}
expect_stdout: "PASS"
node_version: ">=8"
}
issue_4377: {
options = {
dead_code: true,
inline: true,
side_effects: true,
}
input: {
console.log(typeof function() {
return function() {
f;
async function f() {}
return f();
}();
}().then);
}
expect: {
console.log(typeof function() {
return f();
async function f() {}
}().then);
}
expect_stdout: "function"
node_version: ">=8"
}
issue_4406: {
options = {
merge_vars: true,
}
input: {
A = "PASS";
B = "FAIL";
(function() {
var a, b;
a = A;
(async function({
[console.log(a)]: {},
}) {})((b = B) && { undefined: b });
})();
}
expect: {
A = "PASS";
B = "FAIL";
(function() {
var a, b;
a = A;
(async function({
[console.log(a)]: {},
}) {})((b = B) && { undefined: b });
})();
}
expect_stdout: "PASS"
node_version: ">=8"
}
issue_4417: {
options = {
inline: true,
}
input: {
(async function() {
console.log(function() {
return await => 0;
}().prototype);
})();
}
expect: {
(async function() {
console.log(function() {
return await => 0;
}().prototype);
})();
}
expect_stdout: "undefined"
node_version: ">=8"
}

View File

@@ -153,3 +153,31 @@ issue_3690: {
} }
expect_stdout: "PASS" expect_stdout: "PASS"
} }
issue_4374: {
options = {
booleans: true,
conditionals: true,
if_return: true,
reduce_vars: true,
unused: true,
}
input: {
(function() {
console.log(f());
function f(a) {
if (null) return 0;
if (a) return 1;
return 0;
}
})();
}
expect: {
(function() {
console.log(function(a) {
return !null && a ? 1 : 0;
}());
})();
}
expect_stdout: "0"
}

View File

@@ -346,9 +346,8 @@ collapse_vars_if: {
return "x" != "Bar" + x / 4 ? g9 : g5; return "x" != "Bar" + x / 4 ? g9 : g5;
} }
function f3(x) { function f3(x) {
if (x) { if (x)
return 1; return 1;
}
return 2; return 2;
} }
} }
@@ -4192,9 +4191,8 @@ issue_2436_11: {
if (isCollection(arg1)) { if (isCollection(arg1)) {
var size = arg1, max = arg2, min = 0, res = _randomDataForMatrix(size.valueOf(), min, max, _randomInt); var size = arg1, max = arg2, min = 0, res = _randomDataForMatrix(size.valueOf(), min, max, _randomInt);
return size && true === size.isMatrix ? matrix(res) : res; return size && true === size.isMatrix ? matrix(res) : res;
} else { } else
return _randomInt(min = arg1, max = arg2); return _randomInt(min = arg1, max = arg2);
}
} }
} }
} }
@@ -4310,9 +4308,8 @@ issue_2497: {
function sample() { function sample() {
if (true) if (true)
for (var i = 0; i < 1; ++i) for (var i = 0; i < 1; ++i)
for (var k = 0; k < 1; ++k) { for (var k = 0; k < 1; ++k)
value = (value = 1) ? value + 1 : 0; value = (value = 1) ? value + 1 : 0;
}
else else
for (i = 0; i < 1; ++i) for (i = 0; i < 1; ++i)
for (k = 0; k < 1; ++k) for (k = 0; k < 1; ++k)
@@ -8559,3 +8556,109 @@ issue_4070: {
} }
expect_stdout: "NaN" expect_stdout: "NaN"
} }
issue_4242: {
options = {
collapse_vars: true,
conditionals: true,
reduce_vars: true,
unused: true,
}
input: {
console.log(function() {
if (console)
var a = function(){}, b = (!1 === console || a)();
}());
}
expect: {
console.log(function() {
console && (!1 === console || function(){})();
}());
}
expect_stdout: "undefined"
}
issue_4248: {
options = {
collapse_vars: true,
}
input: {
var a = 0;
try {
a = 1;
b[1];
} catch (e) {
console.log(a);
}
}
expect: {
var a = 0;
try {
a = 1;
b[1];
} catch (e) {
console.log(a);
}
}
expect_stdout: "1"
}
issue_4430_1: {
options = {
collapse_vars: true,
pure_getters: "strict",
}
input: {
function f(a) {
switch (a = 1, arguments[0]) {
case 1:
return "PASS";
case 2:
return "FAIL";
}
}
console.log(f(2));
}
expect: {
function f(a) {
switch (a = 1, arguments[0]) {
case 1:
return "PASS";
case 2:
return "FAIL";
}
}
console.log(f(2));
}
expect_stdout: "PASS"
}
issue_4430_2: {
options = {
collapse_vars: true,
pure_getters: "strict",
}
input: {
function f(a) {
switch (a = 0, arguments[0]) {
case 0:
return "PASS";
case 1:
return "FAIL";
}
}
console.log(f(1));
}
expect: {
function f(a) {
switch (arguments[a = 0]) {
case 0:
return "PASS";
case 1:
return "FAIL";
}
}
console.log(f(1));
}
expect_stdout: "PASS"
}

View File

@@ -55,14 +55,15 @@ ifs_3_should_warn: {
} }
input: { input: {
var x, y; var x, y;
if (x && !(x + "1") && y) { // 1 // 1
if (x && !(x + "1") && y) {
var qq; var qq;
foo(); foo();
} else { } else {
bar(); bar();
} }
// 2
if (x || !!(x + "1") || y) { // 2 if (x || !!(x + "1") || y) {
foo(); foo();
} else { } else {
var jj; var jj;
@@ -71,9 +72,25 @@ ifs_3_should_warn: {
} }
expect: { expect: {
var x, y; var x, y;
var qq; bar(); // 1 // 1
var jj; foo(); // 2 var qq; bar();
// 2
foo(); var jj;
} }
expect_warnings: [
"WARN: + in boolean context always true [test/compress/conditionals.js:3,18]",
"WARN: Boolean && always false [test/compress/conditionals.js:3,12]",
"WARN: Condition left of && always false [test/compress/conditionals.js:3,12]",
"WARN: Condition always false [test/compress/conditionals.js:3,12]",
"WARN: Dropping unreachable code [test/compress/conditionals.js:3,34]",
"WARN: + in boolean context always true [test/compress/conditionals.js:10,19]",
"WARN: Boolean || always true [test/compress/conditionals.js:10,12]",
"WARN: Condition left of || always true [test/compress/conditionals.js:10,12]",
"WARN: Condition always true [test/compress/conditionals.js:10,12]",
"WARN: Dropping unreachable code [test/compress/conditionals.js:12,15]",
"WARN: Dropping side-effect-free statement [test/compress/conditionals.js:3,12]",
"WARN: Dropping side-effect-free statement [test/compress/conditionals.js:10,12]",
]
} }
ifs_4: { ifs_4: {
@@ -1159,7 +1176,7 @@ issue_1645_2: {
expect_stdout: true expect_stdout: true
} }
condition_symbol_matches_consequent: { condition_matches_consequent: {
options = { options = {
conditionals: true, conditionals: true,
} }
@@ -1188,6 +1205,35 @@ condition_symbol_matches_consequent: {
expect_stdout: "3 7 true 4" expect_stdout: "3 7 true 4"
} }
condition_matches_alternative: {
options = {
conditionals: true,
}
input: {
function foo(x, y) {
return x.p ? y[0] : x.p;
}
function bar() {
return g ? h : g;
}
var g = 4;
var h = 5;
console.log(foo({ p: 3 }, [ null ]), foo({ p: 0 }, [ 7 ]), foo({ p: true } , [ false ]), bar());
}
expect: {
function foo(x, y) {
return x.p && y[0];
}
function bar() {
return g && h;
}
var g = 4;
var h = 5;
console.log(foo({ p: 3 }, [ null ]), foo({ p: 0 }, [ 7 ]), foo({ p: true } , [ false ]), bar());
}
expect_stdout: "null 0 false 5"
}
delete_conditional_1: { delete_conditional_1: {
options = { options = {
booleans: true, booleans: true,

1377
test/compress/const.js Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -59,6 +59,9 @@ dead_code_2_should_warn: {
f(); f();
} }
expect_stdout: true expect_stdout: true
expect_warnings: [
"WARN: Dropping unreachable code [test/compress/dead-code.js:8,12]",
]
node_version: "<=4" node_version: "<=4"
} }
@@ -89,11 +92,21 @@ dead_code_constant_boolean_should_warn_more: {
function bar() {} function bar() {}
// nothing for the while // nothing for the while
// as for the for, it should keep: // as for the for, it should keep:
var moo;
var x = 10, y; var x = 10, y;
var moo;
bar(); bar();
} }
expect_stdout: true expect_stdout: true
expect_warnings: [
"WARN: + in boolean context always true [test/compress/dead-code.js:1,33]",
"WARN: Boolean || always true [test/compress/dead-code.js:1,16]",
"WARN: Dropping unreachable code [test/compress/dead-code.js:1,45]",
"WARN: Boolean expression always true [test/compress/dead-code.js:6,47]",
"WARN: Boolean && always false [test/compress/dead-code.js:6,28]",
"WARN: Dropping unreachable code [test/compress/dead-code.js:6,63]",
"WARN: Dropping side-effect-free statement [test/compress/dead-code.js:1,15]",
"WARN: Dropping side-effect-free statement [test/compress/dead-code.js:6,28]",
]
node_version: "<=4" node_version: "<=4"
} }
@@ -1362,3 +1375,27 @@ issue_4051: {
} }
expect_stdout: "PASS" expect_stdout: "PASS"
} }
issue_4366: {
options = {
dead_code: true,
}
input: {
function f() {
return "PASS";
({
p: 42,
get p() {},
});
}
console.log(f());
}
expect: {
function f() {
return "PASS";
}
console.log(f());
}
expect_stdout: "PASS"
node_version: ">=4"
}

File diff suppressed because it is too large Load Diff

View File

@@ -2993,6 +2993,38 @@ issue_4146: {
expect_stdout: "function" expect_stdout: "function"
} }
var_catch_redefined: {
options = {
toplevel: true,
unused: true,
}
input: {
var a = "FAIL";
try {
throw "PASS";
} catch (a) {
function f() {
return a;
}
console.log(a);
}
f();
}
expect: {
var a = "FAIL";
try {
throw "PASS";
} catch (a) {
function f() {
return a;
}
console.log(a);
}
f();
}
expect_stdout: "PASS"
}
single_use_catch_redefined: { single_use_catch_redefined: {
options = { options = {
reduce_vars: true, reduce_vars: true,
@@ -3023,3 +3055,101 @@ single_use_catch_redefined: {
} }
expect_stdout: true expect_stdout: true
} }
issue_4184: {
options = {
reduce_vars: true,
unused: true,
}
input: {
(function() {
var a = function() {}, b = [ a, 1 && b, a = {} ];
try {
throw 42;
} catch (a) {
{
console.log(a);
}
}
})();
}
expect: {
(function() {
var b = [ function() {}, 1 && b, {} ];
try {
throw 42;
} catch (a) {
console.log(a);
}
})();
}
expect_stdout: "42"
}
issue_4235: {
options = {
inline: true,
reduce_vars: true,
unused: true,
varify: true,
}
input: {
(function() {
{
const f = 0;
}
(function f() {
var f = console.log(f);
})();
})();
}
expect: {
(function() {
f = console.log(f),
void 0;
var f;
})();
}
expect_stdout: "undefined"
}
issue_4404: {
options = {
pure_getters: "strict",
unused: true,
}
input: {
function f(a) {
arguments[0] = "PASS";
console.log(a);
}
f("FAIL");
}
expect: {
function f(a) {
arguments[0] = "PASS";
console.log(a);
}
f("FAIL");
}
expect_stdout: "PASS"
}
issue_4413: {
options = {
reduce_vars: true,
unused: true,
}
input: {
console.log(function f(arguments) {
var arguments = function() {};
return arguments.length;
}());
}
expect: {
console.log(function(arguments) {
return function() {}.length;
}());
}
expect_stdout: "0"
}

View File

@@ -3014,3 +3014,106 @@ issue_4119_4: {
} }
expect_stdout: "PASS" expect_stdout: "PASS"
} }
issue_4214: {
options = {
evaluate: true,
reduce_vars: true,
toplevel: true,
unused: true,
}
input: {
function f(a) {
return function() {
try {
return a;
} finally {
var b = 0;
}
}(a++ && this());
}
var c = f();
console.log(c);
}
expect: {
var c = function(a) {
return function() {
try {
return a;
} finally {}
}(a++ && this());
}();
console.log(c);
}
expect_stdout: "NaN"
}
issue_4271: {
options = {
evaluate: true,
unsafe: true,
}
input: {
({
p: null,
q: (console.log("foo"), 42),
p: function() {}
})[console.log("bar"), "p"] && console.log("PASS");
}
expect: {
({
p: null,
q: (console.log("foo"), 42),
p: function() {}
})[console.log("bar"), "p"],
console.log("PASS");
}
expect_stdout: [
"foo",
"bar",
"PASS",
]
}
issue_4393: {
options = {
evaluate: true,
reduce_vars: true,
}
input: {
(function f(a) {
a = "PASS";
console.log(arguments[0]);
})("FAIL");
}
expect: {
(function f(a) {
a = "PASS";
console.log(arguments[0]);
})("FAIL");
}
expect_stdout: "PASS"
}
issue_4422: {
options = {
evaluate: true,
reduce_vars: true,
unused: true,
}
input: {
console.log(function f(a) {
a = "FAIL 1";
arguments[0] = "PASS";
return a;
}("FAIL 2"));
}
expect: {
console.log(function(a) {
a = "FAIL 1";
arguments[0] = "PASS";
return a;
}("FAIL 2"));
}
expect_stdout: "PASS"
}

View File

@@ -521,7 +521,7 @@ issue_2531_2: {
options = { options = {
evaluate: true, evaluate: true,
inline: true, inline: true,
passes: 3, passes: 2,
reduce_funcs: true, reduce_funcs: true,
reduce_vars: true, reduce_vars: true,
side_effects: true, side_effects: true,
@@ -556,9 +556,10 @@ issue_2531_3: {
options = { options = {
evaluate: true, evaluate: true,
inline: true, inline: true,
passes: 3, passes: 2,
reduce_funcs: true, reduce_funcs: true,
reduce_vars: true, reduce_vars: true,
sequences: true,
side_effects: true, side_effects: true,
toplevel: true, toplevel: true,
unused: true, unused: true,
@@ -2081,7 +2082,7 @@ issue_3016_1: {
var b = 1; var b = 1;
do { do {
3[b]; 3[b];
} while(0); } while (0);
console.log(b); console.log(b);
} }
expect_stdout: "1" expect_stdout: "1"
@@ -2112,7 +2113,7 @@ issue_3016_2: {
do { do {
a = 3, a = 3,
a[b]; a[b];
} while(0); } while (0);
var a; var a;
console.log(b); console.log(b);
} }
@@ -2145,7 +2146,7 @@ issue_3016_2_ie8: {
do { do {
a = 3, a = 3,
a[b]; a[b];
} while(0); } while (0);
var a; var a;
console.log(b); console.log(b);
} }
@@ -2175,7 +2176,7 @@ issue_3016_3: {
var b = 1; var b = 1;
do { do {
console.log((a = void 0, a ? "FAIL" : a = "PASS")); console.log((a = void 0, a ? "FAIL" : a = "PASS"));
} while(b--); } while (b--);
var a; var a;
} }
expect_stdout: [ expect_stdout: [
@@ -2208,7 +2209,7 @@ issue_3016_3_ie8: {
var b = 1; var b = 1;
do { do {
console.log((a = void 0, a ? "FAIL" : a = "PASS")); console.log((a = void 0, a ? "FAIL" : a = "PASS"));
} while(b--); } while (b--);
var a; var a;
} }
expect_stdout: [ expect_stdout: [
@@ -3321,9 +3322,7 @@ issue_3506_1: {
} }
expect: { expect: {
var a = "FAIL"; var a = "FAIL";
!function(b) { a && (a = "PASS");
b && (a = "PASS");
}(a);
console.log(a); console.log(a);
} }
expect_stdout: "PASS" expect_stdout: "PASS"
@@ -4987,3 +4986,240 @@ catch_defun: {
} }
expect_stdout: true expect_stdout: true
} }
catch_no_argname: {
options = {
inline: true,
reduce_vars: true,
toplevel: true,
unused: true,
}
input: {
var a = "PASS";
function f() {
return a;
}
try {
throw a;
} catch {
function g() {
return a;
}
console.log(a, f(), g());
}
console.log(a, f(), g());
}
expect: {
var a = "PASS";
try {
throw a;
} catch {
console.log(a, a, a);
}
console.log(a, a, a);
}
expect_stdout: [
"PASS PASS PASS",
"PASS PASS PASS",
]
node_version: ">=10"
}
issue_4186: {
options = {
conditionals: true,
inline: true,
reduce_funcs: true,
reduce_vars: true,
sequences: true,
unused: true,
}
input: {
console.log(typeof function() {
return function() {
function f() {
if (1)
g();
else
(function() {
return f;
});
}
return f;
function g() {
if (1) {
if (0)
h;
else
h();
var key = 0;
}
}
function h() {
return factory;
}
};
}()());
}
expect: {
console.log(typeof function() {
return function f() {
1 ? void (1 && (0 ? h : h(), 0)) : function() {
return f;
};
};
function h() {
return factory;
}
}());
}
expect_stdout: "function"
}
issue_4233: {
options = {
functions: true,
reduce_vars: true,
unused: true,
}
input: {
(function() {
try {
var a = function() {};
try {
throw 42;
} catch (a) {
(function() {
console.log(typeof a);
})();
var a;
}
} catch (e) {}
})();
}
expect: {
(function() {
try {
var a = function() {};
try {
throw 42;
} catch (a) {
(function() {
console.log(typeof a);
})();
var a;
}
} catch (e) {}
})();
}
expect_stdout: "number"
}
issue_4259: {
options = {
collapse_vars: true,
functions: true,
reduce_vars: true,
toplevel: true,
unused: true,
}
input: {
var a = function b() {
var c = b;
for (b in c);
};
a();
console.log(typeof a);
}
expect: {
function a() {
for (a in a);
}
a();
console.log(typeof a);
}
expect_stdout: "function"
}
issue_4261: {
options = {
inline: true,
reduce_funcs: true,
reduce_vars: true,
toplevel: true,
unused: true,
}
input: {
try {
throw 42;
} catch (e) {
(function() {
function f() {
e.p;
}
function g() {
while (f());
}
(function() {
while (console.log(g()));
})();
})();
}
}
expect: {
try {
throw 42;
} catch (e) {
(function() {
function g() {
while (void e.p);
}
(function() {
while (console.log(g()));
})();
})();
}
}
expect_stdout: true
}
issue_4265: {
options = {
conditionals: true,
dead_code: true,
inline: true,
sequences: true,
}
input: {
function f() {
console;
if ([ function() {
return this + console.log(a);
a;
var a;
}() ]);
return 0;
}
f();
}
expect: {
function f() {
return console, function() {
return console.log(a);
var a;
}(), 0;
}
f();
}
expect_stdout: "undefined"
}
trailing_comma: {
input: {
new function(a, b,) {
console.log(b, a,);
}(42, "PASS",);
}
expect_exact: 'new function(a,b){console.log(b,a)}(42,"PASS");'
expect_stdout: "PASS 42"
}

View File

@@ -297,6 +297,33 @@ name_collision_3: {
expect_stdout: "true 4 6" expect_stdout: "true 4 6"
} }
name_collision_4: {
options = {
hoist_props: true,
reduce_vars: true,
}
input: {
console.log(function() {
var o = {
p: 0,
q: "PASS",
};
return function(o_p) {
if (!o.p) return o_p;
}(o.q);
}());
}
expect: {
console.log(function() {
var o_p$0 = 0, o_q = "PASS";
return function(o_p) {
if (!o_p$0) return o_p;
}(o_q);
}());
}
expect_stdout: "PASS"
}
contains_this_1: { contains_this_1: {
options = { options = {
evaluate: true, evaluate: true,

View File

@@ -588,7 +588,6 @@ issue_3197_1: {
ie8: false, ie8: false,
} }
input: { input: {
var window = {};
!function() { !function() {
function Foo() { function Foo() {
console.log(this instanceof Foo); console.log(this instanceof Foo);
@@ -598,7 +597,6 @@ issue_3197_1: {
new window.Foo(); new window.Foo();
} }
expect: { expect: {
var window = {};
window.Foo = function o() { window.Foo = function o() {
console.log(this instanceof o); console.log(this instanceof o);
}; };
@@ -619,7 +617,6 @@ issue_3197_1_ie8: {
ie8: true, ie8: true,
} }
input: { input: {
var window = {};
!function() { !function() {
function Foo() { function Foo() {
console.log(this instanceof Foo); console.log(this instanceof Foo);
@@ -629,7 +626,6 @@ issue_3197_1_ie8: {
new window.Foo(); new window.Foo();
} }
expect: { expect: {
var window = {};
window.Foo = function Foo() { window.Foo = function Foo() {
console.log(this instanceof Foo); console.log(this instanceof Foo);
}; };
@@ -2819,3 +2815,88 @@ direct_inline_catch_redefined: {
} }
expect_stdout: true expect_stdout: true
} }
issue_4186: {
options = {
dead_code: true,
evaluate: true,
ie8: true,
reduce_vars: true,
toplevel: true,
unused: true,
}
mangle = {
ie8: true,
toplevel: true,
}
input: {
function f() {
(function NaN() {
var a = 1;
while (a--)
try {} finally {
console.log(0/0);
var b;
}
})(f);
}
f();
NaN;
}
expect: {
(function() {
(function NaN() {
var n = 1;
while (n--)
console.log(0/0);
})();
})();
NaN;
}
expect_stdout: "NaN"
}
issue_4235: {
options = {
ie8: true,
unused: true,
}
input: {
try {} catch (e) {}
console.log(function e() {
var e = 0;
}());
}
expect: {
try {} catch (e) {}
console.log(function e() {}());
}
expect_stdout: "undefined"
}
issue_4250: {
options = {
ie8: true,
loops: true,
unused: true,
}
input: {
console.log(function f() {
(function() {
for (f in "f");
})();
return f;
var f;
}());
}
expect: {
console.log(function f() {
(function() {
for (f in "f");
})();
return f;
var f;
}());
}
expect_stdout: "0"
}

View File

@@ -39,7 +39,7 @@ non_hoisted_function_after_return: {
"WARN: Dropping unreachable code [test/compress/issue-1034.js:4,16]", "WARN: Dropping unreachable code [test/compress/issue-1034.js:4,16]",
"WARN: Dropping unreachable code [test/compress/issue-1034.js:7,16]", "WARN: Dropping unreachable code [test/compress/issue-1034.js:7,16]",
"WARN: Dropping unreachable code [test/compress/issue-1034.js:10,12]", "WARN: Dropping unreachable code [test/compress/issue-1034.js:10,12]",
"WARN: Dropping unused function UnusedFunction [test/compress/issue-1034.js:11,21]" "WARN: Dropping unused function UnusedFunction [test/compress/issue-1034.js:11,21]",
] ]
} }
@@ -84,19 +84,16 @@ non_hoisted_function_after_return_2a: {
} }
} }
expect_warnings: [ expect_warnings: [
"WARN: Dropping unreachable code [test/compress/issue-1034.js:4,16]", "WARN: Dropping initialization in unreachable code [test/compress/issue-1034.js:4,16]",
"WARN: Declarations in unreachable code! [test/compress/issue-1034.js:4,16]", "WARN: Dropping initialization in unreachable code [test/compress/issue-1034.js:7,16]",
"WARN: Dropping unreachable code [test/compress/issue-1034.js:7,16]",
"WARN: Declarations in unreachable code! [test/compress/issue-1034.js:7,16]",
"WARN: Dropping unused variable a [test/compress/issue-1034.js:4,20]", "WARN: Dropping unused variable a [test/compress/issue-1034.js:4,20]",
"WARN: Dropping unused function nope [test/compress/issue-1034.js:11,21]", "WARN: Dropping unused function nope [test/compress/issue-1034.js:11,21]",
"INFO: pass 0: last_count: Infinity, count: 36", "INFO: pass 0: last_count: Infinity, count: 35",
"WARN: Dropping unreachable code [test/compress/issue-1034.js:9,12]", "WARN: Dropping initialization in unreachable code [test/compress/issue-1034.js:9,12]",
"WARN: Declarations in unreachable code! [test/compress/issue-1034.js:9,12]",
"WARN: Dropping unreachable code [test/compress/issue-1034.js:12,12]", "WARN: Dropping unreachable code [test/compress/issue-1034.js:12,12]",
"INFO: Dropping unused variable b [test/compress/issue-1034.js:7,20]", "INFO: Dropping unused variable b [test/compress/issue-1034.js:7,20]",
"INFO: Dropping unused variable c [test/compress/issue-1034.js:9,16]", "INFO: Dropping unused variable c [test/compress/issue-1034.js:9,16]",
"INFO: pass 1: last_count: 36, count: 18", "INFO: pass 1: last_count: 35, count: 18",
] ]
} }
@@ -138,10 +135,7 @@ non_hoisted_function_after_return_2b: {
} }
} }
expect_warnings: [ expect_warnings: [
"WARN: Dropping unreachable code [test/compress/issue-1034.js:6,16]", "WARN: Dropping initialization in unreachable code [test/compress/issue-1034.js:8,12]",
"WARN: Declarations in unreachable code! [test/compress/issue-1034.js:6,16]",
"WARN: Dropping unreachable code [test/compress/issue-1034.js:8,12]",
"WARN: Declarations in unreachable code! [test/compress/issue-1034.js:8,12]",
"WARN: Dropping unreachable code [test/compress/issue-1034.js:12,12]", "WARN: Dropping unreachable code [test/compress/issue-1034.js:12,12]",
] ]
} }
@@ -242,19 +236,16 @@ non_hoisted_function_after_return_2a_strict: {
} }
expect_stdout: "5 6" expect_stdout: "5 6"
expect_warnings: [ expect_warnings: [
"WARN: Dropping unreachable code [test/compress/issue-1034.js:5,16]", "WARN: Dropping initialization in unreachable code [test/compress/issue-1034.js:5,16]",
"WARN: Declarations in unreachable code! [test/compress/issue-1034.js:5,16]", "WARN: Dropping initialization in unreachable code [test/compress/issue-1034.js:8,16]",
"WARN: Dropping unreachable code [test/compress/issue-1034.js:8,16]",
"WARN: Declarations in unreachable code! [test/compress/issue-1034.js:8,16]",
"WARN: Dropping unused variable a [test/compress/issue-1034.js:5,20]", "WARN: Dropping unused variable a [test/compress/issue-1034.js:5,20]",
"WARN: Dropping unused function nope [test/compress/issue-1034.js:12,21]", "WARN: Dropping unused function nope [test/compress/issue-1034.js:12,21]",
"INFO: pass 0: last_count: Infinity, count: 47", "INFO: pass 0: last_count: Infinity, count: 46",
"WARN: Dropping unreachable code [test/compress/issue-1034.js:10,12]", "WARN: Dropping initialization in unreachable code [test/compress/issue-1034.js:10,12]",
"WARN: Declarations in unreachable code! [test/compress/issue-1034.js:10,12]",
"WARN: Dropping unreachable code [test/compress/issue-1034.js:13,12]", "WARN: Dropping unreachable code [test/compress/issue-1034.js:13,12]",
"INFO: Dropping unused variable b [test/compress/issue-1034.js:8,20]", "INFO: Dropping unused variable b [test/compress/issue-1034.js:8,20]",
"INFO: Dropping unused variable c [test/compress/issue-1034.js:10,16]", "INFO: Dropping unused variable c [test/compress/issue-1034.js:10,16]",
"INFO: pass 1: last_count: 47, count: 29", "INFO: pass 1: last_count: 46, count: 29",
] ]
} }
@@ -301,10 +292,7 @@ non_hoisted_function_after_return_2b_strict: {
} }
expect_stdout: "5 6" expect_stdout: "5 6"
expect_warnings: [ expect_warnings: [
"WARN: Dropping unreachable code [test/compress/issue-1034.js:7,16]", "WARN: Dropping initialization in unreachable code [test/compress/issue-1034.js:9,12]",
"WARN: Declarations in unreachable code! [test/compress/issue-1034.js:7,16]",
"WARN: Dropping unreachable code [test/compress/issue-1034.js:9,12]",
"WARN: Declarations in unreachable code! [test/compress/issue-1034.js:9,12]",
"WARN: Dropping unreachable code [test/compress/issue-1034.js:13,12]", "WARN: Dropping unreachable code [test/compress/issue-1034.js:13,12]",
] ]
} }

View File

@@ -151,15 +151,18 @@ Infinity_not_in_with_scope: {
unused: true, unused: true,
} }
input: { input: {
var o = { Infinity: 'oInfinity' }; var o = { Infinity: "FAIL" };
var vInfinity = "Infinity"; var vInfinity = "Infinity";
vInfinity = Infinity; vInfinity = Infinity;
console.log(vInfinity);
} }
expect: { expect: {
var o = { Infinity: 'oInfinity' } var o = { Infinity: "FAIL" };
var vInfinity = "Infinity" var vInfinity = "Infinity";
vInfinity = 1/0 vInfinity = 1/0;
console.log(vInfinity);
} }
expect_stdout: "Infinity"
} }
Infinity_in_with_scope: { Infinity_in_with_scope: {
@@ -167,15 +170,18 @@ Infinity_in_with_scope: {
unused: true, unused: true,
} }
input: { input: {
var o = { Infinity: 'oInfinity' }; var o = { Infinity: "PASS" };
var vInfinity = "Infinity"; var vInfinity = "Infinity";
with (o) { vInfinity = Infinity; } with (o) { vInfinity = Infinity; }
console.log(vInfinity);
} }
expect: { expect: {
var o = { Infinity: 'oInfinity' } var o = { Infinity: "PASS" };
var vInfinity = "Infinity" var vInfinity = "Infinity";
with (o) vInfinity = Infinity with (o) vInfinity = Infinity;
console.log(vInfinity);
} }
expect_stdout: "PASS"
} }
assorted_Infinity_NaN_undefined_in_with_scope: { assorted_Infinity_NaN_undefined_in_with_scope: {

View File

@@ -525,7 +525,7 @@ issue_2506: {
function f0(bar) { function f0(bar) {
(function() { (function() {
(function() { (function() {
if (false <= 0/0 & this >> 1 >= 0) if (false <= NaN & this >> 1 >= 0)
c++; c++;
})(c++); })(c++);
})(); })();
@@ -1452,3 +1452,37 @@ issue_3619: {
} }
expect_stdout: "PASS" expect_stdout: "PASS"
} }
issue_4353_1: {
options = {
keep_fargs: "strict",
reduce_vars: true,
unused: true,
}
input: {
console.log(function f(a) {}.length);
}
expect: {
console.log(function(a) {}.length);
}
expect_stdout: "1"
}
issue_4353_2: {
options = {
keep_fargs: "strict",
reduce_vars: true,
unused: true,
}
input: {
(function f(a) {
while (console.log("PASS"));
})();
}
expect: {
(function() {
while (console.log("PASS"));
})();
}
expect_stdout: "PASS"
}

1230
test/compress/let.js Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -201,7 +201,7 @@ evaluate: {
} }
} }
issue_1532: { issue_1532_1: {
options = { options = {
evaluate: true, evaluate: true,
loops: true, loops: true,
@@ -210,18 +210,56 @@ issue_1532: {
function f(x, y) { function f(x, y) {
do { do {
if (x) break; if (x) break;
foo(); console.log(y);
} while (false); } while (false);
} }
f(null, "PASS");
f(42, "FAIL");
}
expect: {
function f(x, y) {
for (; !x && (console.log(y), false););
}
f(null, "PASS");
f(42, "FAIL");
}
expect_stdout: "PASS"
}
issue_1532_2: {
options = {
evaluate: true,
loops: true,
}
input: {
function f(x, y) {
do {
if (x) {
console.log(x);
break;
}
console.log(y);
} while (false);
}
f(null, "PASS");
f(42, "FAIL");
} }
expect: { expect: {
function f(x, y) { function f(x, y) {
do { do {
if (x) break; if (x) {
foo(); console.log(x);
} while (false); break;
}
} while (console.log(y), false);
} }
f(null, "PASS");
f(42, "FAIL");
} }
expect_stdout: [
"PASS",
"42",
]
} }
issue_186: { issue_186: {
@@ -509,8 +547,8 @@ dead_code_condition: {
console.log(a); console.log(a);
} }
expect: { expect: {
var c;
var a = 0, b = 5; var a = 0, b = 5;
var c;
a += 1, 0, a += 1, 0,
console.log(a); console.log(a);
} }
@@ -1014,6 +1052,7 @@ issue_4084: {
options = { options = {
keep_fargs: "strict", keep_fargs: "strict",
loops: true, loops: true,
passes: 2,
reduce_vars: true, reduce_vars: true,
unused: true, unused: true,
} }
@@ -1088,3 +1127,156 @@ issue_4091_2: {
} }
expect_stdout: "undefined" expect_stdout: "undefined"
} }
issue_4182_1: {
options = {
loops: true,
}
input: {
(function() {
do {
try {
return;
} finally {
continue;
}
console.log("FAIL");
} while (0);
console.log("PASS");
})();
}
expect: {
(function() {
do {
try {
return;
} finally {
continue;
}
console.log("FAIL");
} while (0);
console.log("PASS");
})();
}
expect_stdout: "PASS"
}
issue_4182_2: {
options = {
loops: true,
}
input: {
(function() {
L: do {
do {
try {
return;
} finally {
continue L;
}
console.log("FAIL");
} while (0);
console.log("FAIL");
} while (0);
console.log("PASS");
})();
}
expect: {
(function() {
L: do {
do {
try {
return;
} finally {
continue L;
}
} while (console.log("FAIL"), 0);
console.log("FAIL");
} while (0);
console.log("PASS");
})();
}
expect_stdout: "PASS"
}
do_continue: {
options = {
loops: true,
}
input: {
try {
do {
continue;
} while ([ A ]);
} catch (e) {
console.log("PASS");
}
}
expect: {
try {
do {
continue;
} while ([ A ]);
} catch (e) {
console.log("PASS");
}
}
expect_stdout: "PASS"
}
issue_4240: {
options = {
loops: true,
reduce_funcs: true,
reduce_vars: true,
unused: true,
}
input: {
(function(a) {
function f() {
var o = { PASS: 42 };
for (a in o);
}
(function() {
if (f());
})();
console.log(a);
})();
}
expect: {
(function(a) {
(function() {
if (function() {
for (a in { PASS: 42 });
}());
})();
console.log(a);
})();
}
expect_stdout: "PASS"
}
issue_4355: {
options = {
dead_code: true,
evaluate: true,
loops: true,
side_effects: true,
unused: true,
}
input: {
while (function() {
var a;
for (a in console.log("PASS"))
var b = 0;
}())
var c;
}
expect: {
(function() {
console.log("PASS");
})();
var c;
}
expect_stdout: "PASS"
}

View File

@@ -466,7 +466,7 @@ issue_4112: {
var o = e; var o = e;
for (e in o); for (e in o);
var a = function() {}; var a = function() {};
console.log; console.log(typeof a);
return a; return a;
} }
}()); }());
@@ -479,12 +479,15 @@ issue_4112: {
var a = e; var a = e;
for (e in a); for (e in a);
a = function() {}; a = function() {};
console.log; console.log(typeof a);
return a; return a;
} }
}()); }());
} }
expect_stdout: "function" expect_stdout: [
"function",
"function",
]
} }
issue_4115: { issue_4115: {
@@ -3008,3 +3011,175 @@ issue_4168_use_strict: {
} }
expect_stdout: "PASS true 42" expect_stdout: "PASS true 42"
} }
issue_4237_1: {
options = {
merge_vars: true,
}
input: {
console.log(function(a) {
do {
var b = a++;
if (b)
return "FAIL";
continue;
var c = 42;
} while ("undefined" != typeof c);
return "PASS";
}(0));
}
expect: {
console.log(function(a) {
do {
var b = a++;
if (b)
return "FAIL";
continue;
var c = 42;
} while ("undefined" != typeof c);
return "PASS";
}(0));
}
expect_stdout: "PASS"
}
issue_4237_2: {
options = {
dead_code: true,
evaluate: true,
loops: true,
merge_vars: true,
switches: true,
}
input: {
console.log(function(a) {
do {
switch (0) {
case 0:
var b = a++;
default:
while (b)
return "FAIL";
}
try {
var c = 0;
} finally {
continue;
}
var d = 0;
} while ("undefined" != typeof d);
return "PASS";
}(0));
}
expect: {
console.log(function(a) {
do {
switch (0) {
case 0:
var b = a++;
if (b)
return "FAIL";
}
try {
var c = 0;
} finally {
continue;
}
var d = 0;
} while ("undefined" != typeof d);
return "PASS";
}(0));
}
expect_stdout: "PASS"
}
issue_4253: {
options = {
merge_vars: true,
toplevel: true,
}
input: {
switch (0) {
default:
var a = "FAIL";
a = a && a;
try {
break;
} catch (e) {}
var b = 42;
}
console.log(b);
}
expect: {
switch (0) {
default:
var a = "FAIL";
a = a && a;
try {
break;
} catch (e) {}
var b = 42;
}
console.log(b);
}
expect_stdout: "undefined"
}
issue_4255: {
options = {
dead_code: true,
loops: true,
merge_vars: true,
toplevel: true,
}
input: {
L: for (var a = 2; --a;)
for (var b = 0; console.log(b); --b)
break L;
}
expect: {
L: for (var a = 2; --a;) {
var b = 0;
if (console.log(b))
break L;
}
}
expect_stdout: "0"
}
issue_4257: {
options = {
merge_vars: true,
toplevel: true,
}
input: {
var a = 0;
for (var i = 0; i < 2; i++)
switch (--a) {
case 0:
var b = 0;
break;
case 0:
default:
var c = 1 + (0 | (b && A));
console.log(c);
}
}
expect: {
var a = 0;
for (var i = 0; i < 2; i++)
switch (--a) {
case 0:
var b = 0;
break;
case 0:
default:
var c = 1 + (0 | (b && A));
console.log(c);
}
}
expect_stdout: [
"1",
"1",
]
}

View File

@@ -1,49 +1,100 @@
hex_numbers_in_parentheses_for_prototype_functions: { parentheses_for_prototype_functions: {
beautify = { beautify = {
beautify: true, beautify: true,
} }
input: { input: {
function f() { (function() {
(-2); console.log((-2));
(-2).toFixed(0); console.log((-2).toFixed(0));
(2); console.log((2));
(2).toFixed(0); console.log((2).toFixed(0));
(0.2); console.log((0.2));
(0.2).toFixed(0); console.log((0.2).toFixed(0));
(2.34e20); console.log((2.34e20));
(2.34e20).toFixed(0); console.log((2.34e20).toFixed(0));
(0.00000002); console.log((0.00000002));
(0.00000002).toFixed(0); console.log((0.00000002).toFixed(0));
(1000000000000000128); console.log((1000000000000000128));
(1000000000000000128).toFixed(0); console.log((1000000000000000128).toFixed(0));
(-1000000000000000128); console.log((-1000000000000000128));
(-1000000000000000128).toFixed(0); console.log((-1000000000000000128).toFixed(0));
} })();
} }
expect_exact: [ expect_exact: [
"function f() {", "(function() {",
" -2;", " console.log(-2);",
" (-2).toFixed(0);", " console.log((-2).toFixed(0));",
" 2;", " console.log(2);",
" 2..toFixed(0);", " console.log(2..toFixed(0));",
" .2;", " console.log(.2);",
" .2.toFixed(0);", " console.log(.2.toFixed(0));",
" 234e18;", " console.log(234e18);",
" 234e18.toFixed(0);", " console.log(234e18.toFixed(0));",
" 2e-8;", " console.log(2e-8);",
" 2e-8.toFixed(0);", " console.log(2e-8.toFixed(0));",
" 0xde0b6b3a7640080;", " console.log(0xde0b6b3a7640080);",
" (0xde0b6b3a7640080).toFixed(0);", " console.log(0xde0b6b3a7640080.toFixed(0));",
" -0xde0b6b3a7640080;", " console.log(-0xde0b6b3a7640080);",
" (-0xde0b6b3a7640080).toFixed(0);", " console.log((-0xde0b6b3a7640080).toFixed(0));",
"}", "})();",
] ]
expect_stdout: true
}
parentheses_for_prototype_functions_galio: {
beautify = {
beautify: true,
galio: true,
}
input: {
(function() {
console.log((-2));
console.log((-2).toFixed(0));
console.log((2));
console.log((2).toFixed(0));
console.log((0.2));
console.log((0.2).toFixed(0));
console.log((2.34e20));
console.log((2.34e20).toFixed(0));
console.log((0.00000002));
console.log((0.00000002).toFixed(0));
console.log((1000000000000000128));
console.log((1000000000000000128).toFixed(0));
console.log((-1000000000000000128));
console.log((-1000000000000000128).toFixed(0));
})();
}
expect_exact: [
"(function() {",
" console.log(-2);",
" console.log((-2).toFixed(0));",
" console.log(2);",
" console.log(2..toFixed(0));",
" console.log(.2);",
" console.log(.2.toFixed(0));",
" console.log(234e18);",
" console.log(234e18.toFixed(0));",
" console.log(2e-8);",
" console.log(2e-8.toFixed(0));",
" console.log(0xde0b6b3a7640080);",
" console.log((0xde0b6b3a7640080).toFixed(0));",
" console.log(-0xde0b6b3a7640080);",
" console.log((-0xde0b6b3a7640080).toFixed(0));",
"})();",
]
expect_stdout: true
} }
comparisons: { comparisons: {

View File

@@ -45,8 +45,8 @@ duplicate_key_strict: {
"use strict"; "use strict";
var o = { var o = {
a: 1, a: 1,
b: 2,
a: 3, a: 3,
b: 2,
}; };
for (var k in o) for (var k in o)
console.log(k, o[k]); console.log(k, o[k]);
@@ -221,3 +221,237 @@ numeric_literal: {
"8 7 8", "8 7 8",
] ]
} }
evaluate_computed_key: {
options = {
evaluate: true,
objects: true,
}
input: {
console.log({
["foo" + "bar"]: "PASS",
}.foobar);
}
expect: {
console.log({
foobar: "PASS",
}.foobar);
}
expect_stdout: "PASS"
node_version: ">=4"
}
keep_computed_key: {
options = {
side_effects: true,
}
input: {
({
[console.log("PASS")]: 42,
});
}
expect: {
console.log("PASS");
}
expect_stdout: "PASS"
node_version: ">=4"
}
shorthand_keywords: {
options = {
evaluate: true,
reduce_vars: true,
toplevel: true,
unsafe: true,
unused: true,
}
input: {
var async = 1, get = 2, set = 3, o = {
async,
get,
set,
};
console.log(o.async, o.get, o.set);
}
expect: {
console.log(1, 2, 3);
}
expect_stdout: "1 2 3"
node_version: ">=6"
}
issue_4269_1: {
options = {
evaluate: true,
objects: true,
}
input: {
console.log({
get 0() {
return "FAIL";
},
[0]: "PASS",
}[0]);
}
expect: {
console.log({
get 0() {
return "FAIL";
},
[0]: "PASS",
}[0]);
}
expect_stdout: "PASS"
node_version: ">=4"
}
issue_4269_2: {
options = {
evaluate: true,
objects: true,
}
input: {
console.log({
get [0]() {
return "FAIL";
},
0: "PASS",
}[0]);
}
expect: {
console.log({
get [0]() {
return "FAIL";
},
0: "PASS",
}[0]);
}
expect_stdout: "PASS"
node_version: ">=4"
}
issue_4269_3: {
options = {
evaluate: true,
objects: true,
}
input: {
console.log({
["foo"]: "bar",
get 42() {
return "FAIL";
},
42: "PASS",
}[42]);
}
expect: {
console.log({
foo: "bar",
get [42]() {
return "FAIL";
},
42: "PASS",
}[42]);
}
expect_stdout: "PASS"
node_version: ">=4"
}
issue_4269_4: {
options = {
evaluate: true,
objects: true,
}
input: {
console.log({
get 42() {
return "FAIL";
},
["foo"]: "bar",
42: "PASS",
}[42]);
}
expect: {
console.log({
get 42() {
return "FAIL";
},
foo: "bar",
[42]: "PASS",
}[42]);
}
expect_stdout: "PASS"
node_version: ">=4"
}
issue_4269_5: {
options = {
evaluate: true,
objects: true,
}
input: {
console.log({
get 42() {
return "FAIL";
},
[console]: "bar",
42: "PASS",
}[42]);
}
expect: {
console.log({
get 42() {
return "FAIL";
},
[console]: "bar",
42: "PASS",
}[42]);
}
expect_stdout: "PASS"
node_version: ">=4"
}
issue_4380: {
options = {
evaluate: true,
objects: true,
}
input: {
console.log({
get 0() {
return "FAIL 1";
},
0: "FAIL 2",
[0]: "PASS",
}[0]);
}
expect: {
console.log({
get 0() {
return "FAIL 1";
},
[0]: ("FAIL 2", "PASS"),
}[0]);
}
expect_stdout: "PASS"
node_version: ">=4"
}
issue_4415: {
options = {
evaluate: true,
objects: true,
}
input: {
console.log({
["00"]: "FAIL",
}[0] || "PASS");
}
expect: {
console.log({
"00": "FAIL",
}[0] || "PASS");
}
expect_stdout: "PASS"
node_version: ">=4"
}

View File

@@ -1123,11 +1123,7 @@ new_this: {
} }
}.f(42); }.f(42);
} }
expect: { expect: {}
new function(a) {
this.a = a;
}(42);
}
} }
issue_2513: { issue_2513: {

View File

@@ -848,9 +848,8 @@ collapse_vars_1_true: {
} }
expect: { expect: {
function f(a, b) { function f(a, b) {
for (;;) { for (;;)
if (a.g() || b.p) break; if (a.g() || b.p) break;
}
} }
} }
} }

View File

@@ -1999,7 +1999,7 @@ issue_1606: {
var a, b; var a, b;
function g(){}; function g(){};
b = 2; b = 2;
x(b); x(2);
} }
} }
} }
@@ -7535,3 +7535,69 @@ global_assign: {
} }
expect_stdout: "PASS" expect_stdout: "PASS"
} }
issue_4188_1: {
options = {
reduce_vars: true,
unused: true,
}
input: {
(function() {
try {
while (A)
var a = function() {}, b = a;
} catch (a) {
console.log(function() {
return typeof a;
}(), typeof b);
}
})();
}
expect: {
(function() {
try {
while (A)
var a = function() {}, b = a;
} catch (a) {
console.log(function() {
return typeof a;
}(), typeof b);
}
})();
}
expect_stdout: "object undefined"
}
issue_4188_2: {
options = {
reduce_vars: true,
unused: true,
}
input: {
(function() {
try {
throw 42;
} catch (a) {
console.log(function() {
return typeof a;
}(), typeof b);
}
while (!console)
var a = function() {}, b = a;
})();
}
expect: {
(function() {
try {
throw 42;
} catch (a) {
console.log(function() {
return typeof a;
}(), typeof b);
}
while (!console)
var a = function() {}, b = a;
})();
}
expect_stdout: "number undefined"
}

View File

@@ -416,3 +416,93 @@ issue_4008: {
"PASS", "PASS",
] ]
} }
trim_new: {
options = {
side_effects: true,
}
input: {
new function(a) {
console.log(a);
}("PASS");
}
expect: {
(function(a) {
console.log(a);
})("PASS");
}
expect_stdout: "PASS"
}
issue_4325: {
options = {
keep_fargs: "strict",
passes: 2,
pure_getters: "strict",
reduce_vars: true,
side_effects: true,
unused: true,
}
input: {
(function f() {
(function(b, c) {
try {
c.p = 0;
} catch (e) {
console.log("PASS");
return b;
}
c;
})(f++);
})();
}
expect: {
(function() {
(function() {
try {
(void 0).p = 0;
} catch (e) {
console.log("PASS");
return;
}
})();
})();
}
expect_stdout: "PASS"
}
issue_4366_1: {
options = {
side_effects: true,
}
input: {
({
p: 42,
get p() {},
q: console.log("PASS"),
});
}
expect: {
console.log("PASS");
}
expect_stdout: "PASS"
node_version: ">=4"
}
issue_4366_2: {
options = {
side_effects: true,
}
input: {
({
set p(v) {},
q: console.log("PASS"),
p: 42,
});
}
expect: {
console.log("PASS");
}
expect_stdout: "PASS"
node_version: ">=4"
}

806
test/compress/spread.js Normal file
View File

@@ -0,0 +1,806 @@
collapse_vars_1: {
options = {
collapse_vars: true,
}
input: {
var a;
[ ...a = "PASS", "PASS"].slice();
console.log(a);
}
expect: {
var a;
[ ...a = "PASS", "PASS"].slice();
console.log(a);
}
expect_stdout: "PASS"
node_version: ">=6"
}
collapse_vars_2: {
options = {
collapse_vars: true,
}
input: {
var a = "FAIL";
try {
a = "PASS";
[ ...42, "PASS"].slice();
} catch (e) {
console.log(a);
}
}
expect: {
var a = "FAIL";
try {
a = "PASS";
[ ...42, "PASS"].slice();
} catch (e) {
console.log(a);
}
}
expect_stdout: "PASS"
node_version: ">=6"
}
collapse_vars_3: {
options = {
collapse_vars: true,
}
input: {
var a = "FAIL";
try {
[ ...(a = "PASS", 42), "PASS"].slice();
} catch (e) {
console.log(a);
}
}
expect: {
var a = "FAIL";
try {
[ ...(a = "PASS", 42), "PASS"].slice();
} catch (e) {
console.log(a);
}
}
expect_stdout: "PASS"
node_version: ">=6"
}
collapse_vars_4: {
options = {
collapse_vars: true,
unused: true,
}
input: {
console.log(function(a) {
return a;
}(...[ "PASS", "FAIL" ]));
}
expect: {
console.log(function(a) {
return a;
}(...[ "PASS", "FAIL" ]));
}
expect_stdout: "PASS"
node_version: ">=6"
}
dont_inline: {
options = {
inline: true,
}
input: {
console.log(function(a) {
return a;
}(...[ "PASS", "FAIL" ]));
}
expect: {
console.log(function(a) {
return a;
}(...[ "PASS", "FAIL" ]));
}
expect_stdout: "PASS"
node_version: ">=6"
}
do_inline: {
options = {
inline: true,
spread: true,
}
input: {
console.log(function(a) {
return a;
}(...[ "PASS", "FAIL" ]));
}
expect: {
console.log(("FAIL", "PASS"));
}
expect_stdout: "PASS"
node_version: ">=6"
}
drop_empty_call_1: {
options = {
side_effects: true,
}
input: {
try {
(function() {})(...null);
} catch (e) {
console.log("PASS");
}
}
expect: {
try {
[ ...null ];
} catch (e) {
console.log("PASS");
}
}
expect_stdout: "PASS"
node_version: ">=6"
}
drop_empty_call_2: {
options = {
side_effects: true,
spread: true,
}
input: {
(function() {})(...[ console.log("PASS") ]);
}
expect: {
console.log("PASS");
}
expect_stdout: "PASS"
node_version: ">=6"
}
convert_hole: {
options = {
spread: true,
}
input: {
console.log(...[ "PASS", , 42 ]);
}
expect: {
console.log("PASS", void 0, 42);
}
expect_stdout: "PASS undefined 42"
node_version: ">=6"
}
keep_property_access: {
options = {
properties: true,
side_effects: true,
}
input: {
console.log(function() {
return [ ..."foo" ][0];
}());
}
expect: {
console.log(function() {
return [ ..."foo" ][0];
}());
}
expect_stdout: "f"
node_version: ">=6"
}
keep_fargs: {
options = {
keep_fargs: "strict",
unused: true,
}
input: {
var a = [ "PASS" ];
(function(b, c) {
console.log(c);
})(console, ...a);
}
expect: {
var a = [ "PASS" ];
(function(b, c) {
console.log(c);
})(console, ...a);
}
expect_stdout: "PASS"
node_version: ">=6"
}
reduce_vars_1: {
options = {
reduce_vars: true,
unused: true,
}
input: {
console.log(function(b, c) {
return c ? "PASS" : "FAIL";
}(..."foo"));
}
expect: {
console.log(function(b, c) {
return c ? "PASS" : "FAIL";
}(..."foo"));
}
expect_stdout: "PASS"
node_version: ">=6"
}
reduce_vars_2: {
options = {
conditionals: true,
evaluate: true,
reduce_vars: true,
}
input: {
console.log(function(b, c) {
return c ? "PASS" : "FAIL";
}(..."foo"));
}
expect: {
console.log(function(b, c) {
return c ? "PASS" : "FAIL";
}(..."foo"));
}
expect_stdout: "PASS"
node_version: ">=6"
}
convert_setter: {
options = {
objects: true,
spread: true,
}
input: {
var o = {
...{
set PASS(v) {},
},
};
for (var k in o)
console.log(k, o[k]);
}
expect: {
var o = {
PASS: void 0,
};
for (var k in o)
console.log(k, o[k]);
}
expect_stdout: "PASS undefined"
node_version: ">=8"
}
keep_getter_1: {
options = {
side_effects: true,
}
input: {
({
...{
get p() {
console.log("PASS");
},
},
get q() {
console.log("FAIL");
},
});
}
expect: {
({
...{
get p() {
console.log("PASS");
},
},
});
}
expect_stdout: "PASS"
node_version: ">=8"
}
keep_getter_2: {
options = {
side_effects: true,
}
input: {
({
...(console.log("foo"), {
get p() {
console.log("bar");
},
}),
});
}
expect: {
({
...(console.log("foo"), {
get p() {
console.log("bar");
},
}),
});
}
expect_stdout: [
"foo",
"bar",
]
node_version: ">=8"
}
keep_getter_3: {
options = {
side_effects: true,
}
input: {
({
...function() {
return {
get p() {
console.log("PASS");
},
};
}(),
});
}
expect: {
({
...function() {
return {
get p() {
console.log("PASS");
},
};
}(),
});
}
expect_stdout: "PASS"
node_version: ">=8"
}
keep_getter_4: {
options = {
reduce_vars: true,
side_effects: true,
toplevel: true,
}
input: {
var o = {
get p() {
console.log("PASS");
},
};
({
q: o,
...o,
});
}
expect: {
var o = {
get p() {
console.log("PASS");
},
};
({
...o,
});
}
expect_stdout: "PASS"
node_version: ">=8"
}
keep_accessor: {
options = {
objects: true,
spread: true,
}
input: {
var o = {
...{
get p() {
console.log("GET");
return this.r;
},
set q(v) {
console.log("SET", v);
},
r: 42,
},
r: null,
};
for (var k in o)
console.log(k, o[k]);
}
expect: {
var o = {
...{
get p() {
console.log("GET");
return this.r;
},
set q(v) {
console.log("SET", v);
},
r: 42,
},
r: null,
};
for (var k in o)
console.log(k, o[k]);
}
expect_stdout: [
"GET",
"p 42",
"q undefined",
"r null",
]
node_version: ">=8"
}
object_key_order_1: {
options = {
objects: true,
spread: true,
}
input: {
var o = {
...{},
a: 1,
b: 2,
a: 3,
};
for (var k in o)
console.log(k, o[k]);
}
expect: {
var o = {
a: (1, 3),
b: 2,
};
for (var k in o)
console.log(k, o[k]);
}
expect_stdout: [
"a 3",
"b 2",
]
node_version: ">=8 <=10"
}
object_key_order_2: {
options = {
objects: true,
spread: true,
}
input: {
var o = {
a: 1,
...{},
b: 2,
a: 3,
};
for (var k in o)
console.log(k, o[k]);
}
expect: {
var o = {
a: (1, 3),
b: 2,
};
for (var k in o)
console.log(k, o[k]);
}
expect_stdout: [
"a 3",
"b 2",
]
node_version: ">=8"
}
object_key_order_3: {
options = {
objects: true,
spread: true,
}
input: {
var o = {
a: 1,
b: 2,
...{},
a: 3,
};
for (var k in o)
console.log(k, o[k]);
}
expect: {
var o = {
a: (1, 3),
b: 2,
};
for (var k in o)
console.log(k, o[k]);
}
expect_stdout: [
"a 3",
"b 2",
]
node_version: ">=8"
}
object_key_order_4: {
options = {
objects: true,
spread: true,
}
input: {
var o = {
a: 1,
b: 2,
a: 3,
...{},
};
for (var k in o)
console.log(k, o[k]);
}
expect: {
var o = {
a: (1, 3),
b: 2,
};
for (var k in o)
console.log(k, o[k]);
}
expect_stdout: [
"a 3",
"b 2",
]
node_version: ">=8"
}
object_spread_array: {
options = {
objects: true,
spread: true,
}
input: {
var o = {
...[ "foo", "bar" ],
};
for (var k in o)
console.log(k, o[k]);
}
expect: {
var o = {
...[ "foo", "bar" ],
};
for (var k in o)
console.log(k, o[k]);
}
expect_stdout: [
"0 foo",
"1 bar",
]
node_version: ">=8"
}
object_spread_string: {
options = {
objects: true,
spread: true,
}
input: {
var o = {
..."foo",
};
for (var k in o)
console.log(k, o[k]);
}
expect: {
var o = {
..."foo",
};
for (var k in o)
console.log(k, o[k]);
}
expect_stdout: [
"0 f",
"1 o",
"2 o",
]
node_version: ">=8"
}
unused_var_side_effects: {
options = {
unused: true,
}
input: {
(function f(a) {
var b = {
...a,
};
})({
get p() {
console.log("PASS");
},
});
}
expect: {
(function(a) {
({
...a,
});
})({
get p() {
console.log("PASS");
},
});
}
expect_stdout: "PASS"
node_version: ">=8"
}
issue_4329: {
options = {
objects: true,
spread: true,
}
input: {
console.log({
...{
get 0() {
return "FAIL";
},
...{
0: "PASS",
},
},
}[0]);
}
expect: {
console.log({
...{
get 0() {
return "FAIL";
},
[0]: "PASS",
},
}[0]);
}
expect_stdout: "PASS"
node_version: ">=8"
}
issue_4331: {
options = {
collapse_vars: true,
toplevel: true,
}
input: {
var a = "PASS", b;
console,
b = a;
(function() {
a++;
})(...a);
console.log(b);
}
expect: {
var a = "PASS", b;
console;
(function() {
a++;
})(...b = a);
console.log(b);
}
expect_stdout: "PASS"
node_version: ">=6"
}
issue_4342: {
options = {
side_effects: true,
}
input: {
try {
new function() {}(...42);
} catch (e) {
console.log("PASS");
}
}
expect: {
try {
[ ...42 ];
} catch (e) {
console.log("PASS");
}
}
expect_stdout: "PASS"
node_version: ">=6"
}
issue_4345: {
options = {
objects: true,
spread: true,
}
input: {
console.log({
...{
get 42() {
return "FAIL";
},
...{},
42: "PASS",
},
}[42]);
}
expect: {
console.log({
...{
get 42() {
return "FAIL";
},
[42]: "PASS",
},
}[42]);
}
expect_stdout: "PASS"
node_version: ">=8"
}
issue_4361: {
options = {
reduce_vars: true,
unused: true,
}
input: {
console.log(function() {
var a = console.log("foo");
console;
var b = {
...a,
};
}());
}
expect: {
console.log(function() {
var a = console.log("foo");
console;
({
...a,
});
}());
}
expect_stdout: [
"foo",
"undefined",
]
node_version: ">=8"
}
issue_4363: {
options = {
objects: true,
spread: true,
}
input: {
({
...{
set [console.log("PASS")](v) {},
},
});
}
expect: {
({
[console.log("PASS")]: void 0,
});
}
expect_stdout: "PASS"
node_version: ">=8"
}

View File

@@ -1,3 +1,37 @@
ascii_only_false: {
options = {}
beautify = {
ascii_only: false,
}
input: {
console.log(
"\x000\x001\x007\x008\x00",
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f",
"\x20\x21\x22\x23 ... \x7d\x7e\x7f\x80\x81 ... \xfe\xff\u0fff\uffff"
);
}
expect_exact: 'console.log("\\x000\\x001\\x007\\x008\\0","\\0\x01\x02\x03\x04\x05\x06\x07\\b\\t\\n\\v\\f\\r\x0e\x0f","\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f",\' !"# ... }~\x7f\x80\x81 ... \xfe\xff\u0fff\uffff\');'
expect_stdout: true
}
ascii_only_true: {
options = {}
beautify = {
ascii_only: true,
}
input: {
console.log(
"\x000\x001\x007\x008\x00",
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f",
"\x20\x21\x22\x23 ... \x7d\x7e\x7f\x80\x81 ... \xfe\xff\u0fff\uffff"
);
}
expect_exact: 'console.log("\\x000\\x001\\x007\\x008\\0","\\0\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\b\\t\\n\\v\\f\\r\\x0e\\x0f","\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f",\' !"# ... }~\\x7f\\x80\\x81 ... \\xfe\\xff\\u0fff\\uffff\');'
expect_stdout: true
}
unicode_parse_variables: { unicode_parse_variables: {
options = {} options = {}
input: { input: {
@@ -141,3 +175,35 @@ issue_2569: {
} }
expect_exact: 'new RegExp("[\\udc42-\\udcaa\\udd74-\\udd96\\ude45-\\ude4f\\udea3-\\udecc]");' expect_exact: 'new RegExp("[\\udc42-\\udcaa\\udd74-\\udd96\\ude45-\\ude4f\\udea3-\\udecc]");'
} }
surrogate_pair: {
beautify = {
ascii_only: false,
}
input: {
var \u{2f800} = {
\u{2f801}: "\u{100000}",
};
\u{2f800}.\u{2f802} = "\u{100001}";
console.log(typeof \u{2f800}, \u{2f800}.\u{2f801}, \u{2f800}["\u{2f802}"]);
}
expect_exact: 'var \ud87e\udc00={"\ud87e\udc01":"\udbc0\udc00"};\ud87e\udc00.\ud87e\udc02="\udbc0\udc01";console.log(typeof \ud87e\udc00,\ud87e\udc00.\ud87e\udc01,\ud87e\udc00["\ud87e\udc02"]);'
expect_stdout: "object \udbc0\udc00 \udbc0\udc01"
node_version: ">=4"
}
surrogate_pair_ascii: {
beautify = {
ascii_only: true,
}
input: {
var \u{2f800} = {
\u{2f801}: "\u{100000}",
};
\u{2f800}.\u{2f802} = "\u{100001}";
console.log(typeof \u{2f800}, \u{2f800}.\u{2f801}, \u{2f800}["\u{2f802}"]);
}
expect_exact: 'var \\u{2f800}={"\\ud87e\\udc01":"\\udbc0\\udc00"};\\u{2f800}.\\u{2f802}="\\udbc0\\udc01";console.log(typeof \\u{2f800},\\u{2f800}.\\u{2f801},\\u{2f800}["\\ud87e\\udc02"]);'
expect_stdout: "object \udbc0\udc00 \udbc0\udc01"
node_version: ">=4"
}

411
test/compress/varify.js Normal file
View File

@@ -0,0 +1,411 @@
reduce_merge_const: {
options = {
merge_vars: true,
reduce_vars: true,
toplevel: true,
unused: true,
varify: true,
}
input: {
const a = console;
console.log(typeof a);
var b = typeof a;
console.log(b);
}
expect: {
var b = console;
console.log(typeof b);
b = typeof b;
console.log(b);
}
expect_stdout: [
"object",
"object",
]
}
reduce_merge_let: {
options = {
merge_vars: true,
reduce_vars: true,
toplevel: true,
unused: true,
varify: true,
}
input: {
"use strict";
let a = console;
console.log(typeof a);
var b = typeof a;
console.log(b);
}
expect: {
"use strict";
var b = console;
console.log(typeof b);
b = typeof b;
console.log(b);
}
expect_stdout: [
"object",
"object",
]
node_version: ">=4"
}
reduce_block_const: {
options = {
reduce_vars: true,
toplevel: true,
varify: true,
}
input: {
{
const a = typeof console;
console.log(a);
}
}
expect: {
var a = typeof console;
console.log(a);
}
expect_stdout: "object"
}
reduce_block_let: {
options = {
reduce_vars: true,
toplevel: true,
varify: true,
}
input: {
"use strict";
{
let a = typeof console;
console.log(a);
}
}
expect: {
"use strict";
var a = typeof console;
console.log(a);
}
expect_stdout: "object"
node_version: ">=4"
}
hoist_props_const: {
options = {
hoist_props: true,
passes: 2,
reduce_vars: true,
toplevel: true,
varify: true,
}
input: {
{
const o = {
p: "PASS",
};
console.log(o.p);
}
}
expect: {
var o_p = "PASS";
console.log(o_p);
}
expect_stdout: "PASS"
}
hoist_props_let: {
options = {
hoist_props: true,
passes: 2,
reduce_vars: true,
toplevel: true,
varify: true,
}
input: {
"use strict";
{
let o = {
p: "PASS",
};
console.log(o.p);
}
}
expect: {
"use strict";
var o_p = "PASS";
console.log(o_p);
}
expect_stdout: "PASS"
node_version: ">=4"
}
scope_adjustment_const: {
options = {
conditionals: true,
inline: true,
reduce_vars: true,
toplevel: true,
unused: true,
varify: true,
}
input: {
for (var k in [ 42 ])
console.log(function f() {
if (k) {
const a = 0;
}
}());
}
expect: {
for (var k in [ 42 ])
console.log(void (k && 0));
}
expect_stdout: "undefined"
}
scope_adjustment_let: {
options = {
conditionals: true,
inline: true,
reduce_vars: true,
toplevel: true,
unused: true,
varify: true,
}
input: {
"use strict";
for (var k in [ 42 ])
console.log(function f() {
if (k) {
let a = 0;
}
}());
}
expect: {
"use strict";
for (var k in [ 42 ])
console.log(void (k && 0));
}
expect_stdout: "undefined"
node_version: ">=4"
}
issue_4191_const: {
options = {
functions: true,
reduce_vars: true,
toplevel: true,
unused: true,
varify: true,
}
input: {
const a = function() {};
console.log(typeof a, a());
}
expect: {
function a() {};
console.log(typeof a, a());
}
expect_stdout: "function undefined"
}
issue_4191_let: {
options = {
functions: true,
reduce_vars: true,
toplevel: true,
unused: true,
varify: true,
}
input: {
"use strict";
let a = function() {};
console.log(typeof a, a());
}
expect: {
"use strict";
function a() {};
console.log(typeof a, a());
}
expect_stdout: "function undefined"
node_version: ">=4"
}
forin_const_1: {
options = {
join_vars: true,
reduce_vars: true,
toplevel: true,
varify: true,
}
input: {
const o = {
foo: 42,
bar: "PASS",
};
for (const k in o)
console.log(k, o[k]);
}
expect: {
var o = {
foo: 42,
bar: "PASS",
};
for (const k in o)
console.log(k, o[k]);
}
expect_stdout: true
node_version: ">=4"
}
forin_const_2: {
options = {
join_vars: true,
reduce_vars: true,
toplevel: true,
varify: true,
}
input: {
const o = {
p: 42,
q: "PASS",
};
for (const [ k ] in o)
console.log(k, o[k]);
}
expect: {
var o = {
p: 42,
q: "PASS",
}, k;
for ([ k ] in o)
console.log(k, o[k]);
}
expect_stdout: [
"p 42",
"q PASS",
]
node_version: ">=6"
}
forin_let_1: {
options = {
join_vars: true,
reduce_vars: true,
toplevel: true,
varify: true,
}
input: {
"use strict";
let o = {
foo: 42,
bar: "PASS",
};
for (let k in o)
console.log(k, o[k]);
}
expect: {
"use strict";
var o = {
foo: 42,
bar: "PASS",
}, k;
for (k in o)
console.log(k, o[k]);
}
expect_stdout: [
"foo 42",
"bar PASS",
]
node_version: ">=4"
}
forin_let_2: {
options = {
join_vars: true,
reduce_vars: true,
toplevel: true,
varify: true,
}
input: {
let o = {
p: 42,
q: "PASS",
};
for (let [ k ] in o)
console.log(k, o[k]);
}
expect: {
var o = {
p: 42,
q: "PASS",
}, k;
for ([ k ] in o)
console.log(k, o[k]);
}
expect_stdout: [
"p 42",
"q PASS",
]
node_version: ">=6"
}
issue_4290_1_const: {
options = {
reduce_vars: true,
toplevel: true,
varify: true,
}
input: {
const a = 0;
var a;
}
expect: {
const a = 0;
var a;
}
expect_stdout: true
}
issue_4290_1_let: {
options = {
reduce_vars: true,
toplevel: true,
varify: true,
}
input: {
"use strict";
let a = 0;
var a;
}
expect: {
"use strict";
let a = 0;
var a;
}
expect_stdout: true
node_version: ">=4"
}
drop_forin_let: {
options = {
loops: true,
toplevel: true,
unused: true,
varify: true,
}
input: {
"use strict";
for (let a in console.log("PASS"));
}
expect: {
"use strict";
console.log("PASS");
}
expect_stdout: "PASS"
node_version: ">=4"
}

View File

@@ -0,0 +1,8 @@
function f() {
var { eval } = null;
}
function g() {
"use strict";
var { eval } = 42;
}

View File

@@ -1,2 +1,2 @@
new function(){console.log(3)}; console.log(3);
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInN0ZGluIl0sInNvdXJjZXNDb250ZW50IjpbImNsYXNzIEZvbyB7IGNvbnN0cnVjdG9yKCl7Y29uc29sZS5sb2coMSsyKTt9IH0gbmV3IEZvbygpO1xuIl0sIm5hbWVzIjpbImNvbnNvbGUiLCJsb2ciXSwibWFwcGluZ3MiOiJBQUErQyxJQUFyQyxXQUFnQkEsUUFBUUMsSUFBSSJ9 //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInN0ZGluIl0sInNvdXJjZXNDb250ZW50IjpbImNsYXNzIEZvbyB7IGNvbnN0cnVjdG9yKCl7Y29uc29sZS5sb2coMSsyKTt9IH0gbmV3IEZvbygpO1xuIl0sIm5hbWVzIjpbImNvbnNvbGUiLCJsb2ciXSwibWFwcGluZ3MiOiJBQUEwQkEsUUFBUUMsSUFBSSJ9

View File

@@ -1,2 +1,2 @@
new function(){console.log(3)}; console.log(3);
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInN0ZGluIl0sInNvdXJjZXNDb250ZW50IjpbImNsYXNzIEZvbyB7IGNvbnN0cnVjdG9yKCl7Y29uc29sZS5sb2coMSsyKTt9IH0gbmV3IEZvbygpO1xuIl0sIm5hbWVzIjpbImNvbnNvbGUiLCJsb2ciXSwibWFwcGluZ3MiOiJBQUErQyxJQUFyQyxXQUFnQkEsUUFBUUMsSUFBSSJ9 //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInN0ZGluIl0sInNvdXJjZXNDb250ZW50IjpbImNsYXNzIEZvbyB7IGNvbnN0cnVjdG9yKCl7Y29uc29sZS5sb2coMSsyKTt9IH0gbmV3IEZvbygpO1xuIl0sIm5hbWVzIjpbImNvbnNvbGUiLCJsb2ciXSwibWFwcGluZ3MiOiJBQUEwQkEsUUFBUUMsSUFBSSJ9

View File

@@ -0,0 +1,7 @@
try {
"foo" in 42;
} catch ({
message,
}) {
console.log(message);
}

View File

@@ -0,0 +1,15 @@
// (beautified)
try {
1 in 0;
} catch ({
message: message
}) {
console.log(message);
}
// output: Cannot use 'in' operator to search for '1' in 0
//
// minify: Cannot use 'in' operator to search for '0' in 0
//
// options: {
// "mangle": false
// }

View File

@@ -60,7 +60,7 @@ if (typeof phantom == "undefined") {
var port = server.address().port; var port = server.address().port;
if (debug) { if (debug) {
console.log("http://localhost:" + port + "/"); console.log("http://localhost:" + port + "/");
} else { } else (function install() {
child_process.spawn(process.platform == "win32" ? "npm.cmd" : "npm", [ child_process.spawn(process.platform == "win32" ? "npm.cmd" : "npm", [
"install", "install",
"phantomjs-prebuilt@2.1.14", "phantomjs-prebuilt@2.1.14",
@@ -71,7 +71,10 @@ if (typeof phantom == "undefined") {
], { ], {
stdio: [ "ignore", 1, 2 ] stdio: [ "ignore", 1, 2 ]
}).on("exit", function(code) { }).on("exit", function(code) {
if (code) throw new Error("npm install failed!"); if (code) {
console.log("npm install failed with code", code);
return install();
}
var program = require("phantomjs-prebuilt").exec(process.argv[1], port); var program = require("phantomjs-prebuilt").exec(process.argv[1], port);
program.stdout.pipe(process.stdout); program.stdout.pipe(process.stdout);
program.stderr.pipe(process.stderr); program.stderr.pipe(process.stderr);
@@ -82,7 +85,7 @@ if (typeof phantom == "undefined") {
process.exit(0); process.exit(0);
}); });
}); });
} })();
}); });
server.timeout = 0; server.timeout = 0;
} else { } else {

65
test/mocha/async.js Normal file
View File

@@ -0,0 +1,65 @@
var assert = require("assert");
var UglifyJS = require("../node");
describe("async", function() {
it("Should reject `await` as symbol name within async functions only", function() {
[
"function await() {}",
"function(await) {}",
"function() { await; }",
"function() { await:{} }",
"function() { var await; }",
"function() { function await() {} }",
"function() { try {} catch (await) {} }",
].forEach(function(code) {
var ast = UglifyJS.parse("(" + code + ")();");
assert.strictEqual(ast.TYPE, "Toplevel");
assert.strictEqual(ast.body.length, 1);
assert.strictEqual(ast.body[0].TYPE, "SimpleStatement");
assert.strictEqual(ast.body[0].body.TYPE, "Call");
assert.strictEqual(ast.body[0].body.expression.TYPE, "Function");
assert.throws(function() {
UglifyJS.parse("(async " + code + ")();");
}, function(e) {
return e instanceof UglifyJS.JS_Parse_Error;
}, code);
});
});
it("Should reject `await` expression outside of async functions", function() {
[
"await 42;",
"function f() { await 42; }",
"async function f() { function g() { await 42; } }",
].forEach(function(code) {
assert.throws(function() {
UglifyJS.parse(code);
}, function(e) {
return e instanceof UglifyJS.JS_Parse_Error;
}, code);
});
});
it("Should reject `await` expression directly on computed key of function argument", function() {
[
"function f({ [await 42]: a }) {}",
"async function f({ [await 42]: a }) {}",
].forEach(function(code) {
assert.throws(function() {
UglifyJS.parse(code);
}, function(e) {
return e instanceof UglifyJS.JS_Parse_Error;
}, code);
});
});
it("Should accept `await` expression nested within computed key of function argument", function() {
[
"function f({ [async function() { await 42; }()]: a }) {}",
"async function f({ [async function() { await 42; }()]: a }) {}",
].forEach(function(code) {
var ast = UglifyJS.parse(code);
assert.strictEqual(ast.TYPE, "Toplevel");
assert.strictEqual(ast.body.length, 1);
assert.strictEqual(ast.body[0].argnames.length, 1);
assert.strictEqual(ast.body[0].argnames[0].TYPE, "DestructuredObject");
});
});
});

View File

@@ -573,6 +573,20 @@ describe("bin/uglifyjs", function() {
done(); done();
}); });
}); });
it("Should throw syntax error (var { eval })", function(done) {
var command = uglifyjscmd + " test/input/invalid/destructured_var.js";
exec(command, function(err, stdout, stderr) {
assert.ok(err);
assert.strictEqual(stdout, "");
assert.strictEqual(stderr.split(/\n/).slice(0, 4).join("\n"), [
"Parse error at test/input/invalid/destructured_var.js:7,10",
" var { eval } = 42;",
" ^",
"ERROR: Unexpected eval in strict mode"
].join("\n"));
done();
});
});
it("Should throw syntax error (else)", function(done) { it("Should throw syntax error (else)", function(done) {
var command = uglifyjscmd + " test/input/invalid/else.js"; var command = uglifyjscmd + " test/input/invalid/else.js";
exec(command, function(err, stdout, stderr) { exec(command, function(err, stdout, stderr) {

View File

@@ -28,4 +28,65 @@ describe("Number literals", function() {
assert.throws(test(inputs[i]), error, inputs[i]); assert.throws(test(inputs[i]), error, inputs[i]);
} }
}); });
it("Should parse binary, hexadecimal, octal and underscore correctly", function() {
[
"42",
"4_2",
"052",
"0o52",
"0O52",
"0o5_2",
"0x2a",
"0X2A",
"0x2_a",
"0b101010",
"0B101010",
"0b101_010",
"0.0000000042e+10",
"0.0000000042E+10",
"0.0_000000042e+10",
"0.0000000042e+1_0",
"0.000_000_004_2e+1_0",
"0.000_000_004_2e+1_0-0B101_010+0x2_A-0o5_2+4_2",
].forEach(function(code) {
var result = UglifyJS.minify(code, {
compress: {
expression: true,
},
});
if (result.error) throw result.error;
assert.strictEqual(result.code, "42;");
});
});
it("Should reject invalid use of underscore", function() {
[
"_42",
"_+42",
"+_42",
].forEach(function(code) {
var node = UglifyJS.parse(code, {
expression: true,
});
assert.ok(!node.is_constant(), code);
assert.ok(!(node instanceof UglifyJS.AST_Statement), code);
});
[
"42_",
"4__2",
"0_52",
"05_2",
"0_o52",
"0o_52",
"0.0000000042_e10",
"0.0000000042e_10",
"0.0000000042e_+10",
"0.0000000042e+_10",
].forEach(function(code) {
assert.throws(function() {
UglifyJS.parse(code);
}, function(e) {
return e instanceof UglifyJS.JS_Parse_Error;
}, code);
});
});
}); });

View File

@@ -313,4 +313,12 @@ describe("test/reduce.js", function() {
if (result.error) throw result.error; if (result.error) throw result.error;
assert.strictEqual(result.code, read("test/input/reduce/diff_error.reduced.js")); assert.strictEqual(result.code, read("test/input/reduce/diff_error.reduced.js"));
}); });
it("Should handle destructured catch expressions", function() {
if (semver.satisfies(process.version, "<6")) return;
var result = reduce_test(read("test/input/reduce/destructured_catch.js"), {
mangle: false,
});
if (result.error) throw result.error;
assert.strictEqual(result.code, read("test/input/reduce/destructured_catch.reduced.js"));
});
}); });

View File

@@ -1,64 +1,58 @@
var assert = require("assert"); var assert = require("assert");
var run_code = require("../sandbox").run_code;
var UglifyJS = require("../node"); var UglifyJS = require("../node");
describe("String literals", function() { describe("String literals", function() {
it("Should throw syntax error if a string literal contains a newline", function() { it("Should throw syntax error if a string literal contains a newline", function() {
var inputs = [ [
"'\n'", "'\n'",
"'\r'", "'\r'",
'"\r\n"', '"\r\n"',
"'\u2028'", "'\u2028'",
'"\u2029"' '"\u2029"',
]; ].forEach(function(input) {
assert.throws(function() {
var test = function(input) {
return function() {
var ast = UglifyJS.parse(input); var ast = UglifyJS.parse(input);
}; }, function(e) {
}; return e instanceof UglifyJS.JS_Parse_Error
&& e.message === "Unterminated string constant";
var error = function(e) { });
return e instanceof UglifyJS.JS_Parse_Error });
&& e.message === "Unterminated string constant"; });
}; it("Should handle line continuation correctly", function() {
[
for (var input in inputs) { '"\\\r"',
assert.throws(test(inputs[input]), error); '"\\\n"',
} '"\\\r\n"',
].forEach(function(str) {
var code = "console.log(" + str + ");";
var result = UglifyJS.minify(code);
if (result.error) throw result.error;
assert.strictEqual(run_code(result.code), run_code(code));
});
}); });
it("Should not throw syntax error if a string has a line continuation", function() { it("Should not throw syntax error if a string has a line continuation", function() {
var output = UglifyJS.parse('var a = "a\\\nb";').print_to_string(); var ast = UglifyJS.parse('var a = "a\\\nb";');
assert.equal(output, 'var a="ab";'); assert.equal(ast.print_to_string(), 'var a="ab";');
}); });
it("Should throw error in strict mode if string contains escaped octalIntegerLiteral", function() { it("Should throw error in strict mode if string contains escaped octalIntegerLiteral", function() {
var inputs = [ [
'"use strict";\n"\\76";', '"use strict";\n"\\76";',
'"use strict";\nvar foo = "\\76";', '"use strict";\nvar foo = "\\76";',
'"use strict";\n"\\1";', '"use strict";\n"\\1";',
'"use strict";\n"\\07";', '"use strict";\n"\\07";',
'"use strict";\n"\\011"' '"use strict";\n"\\011"',
]; ].forEach(function(input) {
assert.throws(function() {
var test = function(input) {
return function() {
var output = UglifyJS.parse(input); var output = UglifyJS.parse(input);
} }, function(e) {
}; return e instanceof UglifyJS.JS_Parse_Error
&& e.message === "Legacy octal escape sequences are not allowed in strict mode";
var error = function(e) { });
return e instanceof UglifyJS.JS_Parse_Error });
&& e.message === "Legacy octal escape sequences are not allowed in strict mode";
}
for (var input in inputs) {
assert.throws(test(inputs[input]), error);
}
}); });
it("Should not throw error outside strict mode if string contains escaped octalIntegerLiteral", function() { it("Should not throw error outside strict mode if string contains escaped octalIntegerLiteral", function() {
var tests = [ [
[ ';"\\76";', ';">";' ], [ ';"\\76";', ';">";' ],
[ ';"\\0";', ';"\\0";' ], [ ';"\\0";', ';"\\0";' ],
[ ';"\\08"', ';"\\x008";' ], [ ';"\\08"', ';"\\x008";' ],
@@ -66,19 +60,15 @@ describe("String literals", function() {
[ ';"\\0008"', ';"\\x008";' ], [ ';"\\0008"', ';"\\x008";' ],
[ ';"use\\\n strict";\n"\\07";', ';"use strict";"\07";' ], [ ';"use\\\n strict";\n"\\07";', ';"use strict";"\07";' ],
[ '"use strict" === "use strict";\n"\\76";', '"use strict"==="use strict";">";' ], [ '"use strict" === "use strict";\n"\\76";', '"use strict"==="use strict";">";' ],
]; ].forEach(function(test) {
var ast = UglifyJS.parse(test[0]);
for (var test in tests) { assert.equal(ast.print_to_string(), test[1]);
var output = UglifyJS.parse(tests[test][0]).print_to_string(); });
assert.equal(output, tests[test][1]);
}
}); });
it("Should not throw error when digit is 8 or 9", function() { it("Should not throw error when digit is 8 or 9", function() {
assert.equal(UglifyJS.parse('"use strict";;"\\08"').print_to_string(), '"use strict";;"\\x008";'); assert.equal(UglifyJS.parse('"use strict";;"\\08"').print_to_string(), '"use strict";;"\\x008";');
assert.equal(UglifyJS.parse('"use strict";;"\\09"').print_to_string(), '"use strict";;"\\x009";'); assert.equal(UglifyJS.parse('"use strict";;"\\09"').print_to_string(), '"use strict";;"\\x009";');
}); });
it("Should not unescape unpaired surrogates", function() { it("Should not unescape unpaired surrogates", function() {
var code = []; var code = [];
for (var i = 0; i <= 0xF; i++) { for (var i = 0; i <= 0xF; i++) {
@@ -115,4 +105,33 @@ describe("String literals", function() {
assert.ok(code.length > ascii.code.length); assert.ok(code.length > ascii.code.length);
assert.strictEqual(eval(code), eval(ascii.code)); assert.strictEqual(eval(code), eval(ascii.code));
}); });
it("Should reject invalid Unicode escape sequence", function() {
[
'var foo = "\\u-111"',
'var bar = "\\u{-1}"',
'var baz = "\\ugggg"',
].forEach(function(test) {
assert.throws(function() {
UglifyJS.parse(test);
}, function(e) {
return e instanceof UglifyJS.JS_Parse_Error
&& e.message === "Invalid hex-character pattern in string";
});
});
});
it("Should reject invalid code points in Unicode escape sequence", function() {
[
// A bit over the valid range
'"\\u{110000}"',
// 32-bit overflow resulting in "a"
'"\\u{100000061}"',
].forEach(function(test) {
assert.throws(function() {
UglifyJS.parse(test);
}, function(e) {
return e instanceof UglifyJS.JS_Parse_Error
&& /^Invalid character code: /.test(e.message);
});
});
});
}); });

View File

@@ -5,7 +5,7 @@ describe("tokens", function() {
it("Should give correct positions for accessors", function() { it("Should give correct positions for accessors", function() {
// location 0 1 2 3 4 // location 0 1 2 3 4
// 01234567890123456789012345678901234567890123456789 // 01234567890123456789012345678901234567890123456789
var ast = UglifyJS.parse("var obj = { get latest() { return undefined; } }"); var ast = UglifyJS.parse("var obj = { get [prop]() { return undefined; } }");
// test all AST_ObjectProperty tokens are set as expected // test all AST_ObjectProperty tokens are set as expected
var found = false; var found = false;
ast.walk(new UglifyJS.TreeWalker(function(node) { ast.walk(new UglifyJS.TreeWalker(function(node) {
@@ -13,9 +13,9 @@ describe("tokens", function() {
found = true; found = true;
assert.equal(node.start.pos, 12); assert.equal(node.start.pos, 12);
assert.equal(node.end.endpos, 46); assert.equal(node.end.endpos, 46);
assert(node.key instanceof UglifyJS.AST_SymbolAccessor); assert(node.key instanceof UglifyJS.AST_SymbolRef);
assert.equal(node.key.start.pos, 16); assert.equal(node.key.start.pos, 17);
assert.equal(node.key.end.endpos, 22); assert.equal(node.key.end.endpos, 21);
assert(node.value instanceof UglifyJS.AST_Accessor); assert(node.value instanceof UglifyJS.AST_Accessor);
assert.equal(node.value.start.pos, 22); assert.equal(node.value.start.pos, 22);
assert.equal(node.value.end.endpos, 46); assert.equal(node.value.end.endpos, 46);

View File

@@ -17,7 +17,7 @@ describe("With", function() {
var ast = UglifyJS.parse("with(e) {f(1, 2)}"); var ast = UglifyJS.parse("with(e) {f(1, 2)}");
ast.figure_out_scope(); ast.figure_out_scope();
assert.equal(ast.uses_with, true); assert.equal(ast.uses_with, true);
assert.equal(ast.body[0].expression.scope.uses_with, true); assert.equal(ast.body[0].expression.scope.resolve().uses_with, true);
assert.equal(ast.body[0].body.body[0].body.expression.scope.uses_with, true); assert.equal(ast.body[0].body.body[0].body.expression.scope.resolve().uses_with, true);
}); });
}); });

View File

@@ -18,9 +18,18 @@ var sandbox = require("./sandbox");
Error.stackTraceLimit = Infinity; Error.stackTraceLimit = Infinity;
module.exports = function reduce_test(testcase, minify_options, reduce_options) { module.exports = function reduce_test(testcase, minify_options, reduce_options) {
if (testcase instanceof U.AST_Node) testcase = testcase.print_to_string();
minify_options = minify_options || {}; minify_options = minify_options || {};
reduce_options = reduce_options || {}; reduce_options = reduce_options || {};
var print_options = {};
[
"ie8",
"v8",
"webkit",
].forEach(function(name) {
var value = minify_options[name] || minify_options.output && minify_options.output[name];
if (value) print_options[name] = value;
});
if (testcase instanceof U.AST_Node) testcase = testcase.print_to_string(print_options);
var max_iterations = reduce_options.max_iterations || 1000; var max_iterations = reduce_options.max_iterations || 1000;
var max_timeout = reduce_options.max_timeout || 10000; var max_timeout = reduce_options.max_timeout || 10000;
var warnings = []; var warnings = [];
@@ -95,6 +104,7 @@ module.exports = function reduce_test(testcase, minify_options, reduce_options)
// quick ignores // quick ignores
if (node instanceof U.AST_Accessor) return; if (node instanceof U.AST_Accessor) return;
if (node instanceof U.AST_Destructured) return;
if (node instanceof U.AST_Directive) return; if (node instanceof U.AST_Directive) return;
if (!in_list && node instanceof U.AST_EmptyStatement) return; if (!in_list && node instanceof U.AST_EmptyStatement) return;
if (node instanceof U.AST_Label) return; if (node instanceof U.AST_Label) return;
@@ -114,6 +124,8 @@ module.exports = function reduce_test(testcase, minify_options, reduce_options)
// ignore lvalues // ignore lvalues
if (parent instanceof U.AST_Assign && parent.left === node) return; if (parent instanceof U.AST_Assign && parent.left === node) return;
if (parent instanceof U.AST_DestructuredArray) return;
if (parent instanceof U.AST_DestructuredKeyVal && parent.value === node) return;
if (parent instanceof U.AST_Unary && parent.expression === node) switch (parent.operator) { if (parent instanceof U.AST_Unary && parent.expression === node) switch (parent.operator) {
case "++": case "++":
case "--": case "--":
@@ -121,7 +133,7 @@ module.exports = function reduce_test(testcase, minify_options, reduce_options)
return; return;
} }
// preserve for (var xxx; ...) // preserve for (var xxx; ...)
if (parent instanceof U.AST_For && parent.init === node && node instanceof U.AST_Var) return node; if (parent instanceof U.AST_For && parent.init === node && node instanceof U.AST_Definitions) return node;
// preserve for (xxx in ...) // preserve for (xxx in ...)
if (parent instanceof U.AST_ForIn && parent.init === node) return node; if (parent instanceof U.AST_ForIn && parent.init === node) return node;
@@ -132,7 +144,7 @@ module.exports = function reduce_test(testcase, minify_options, reduce_options)
if (expr && !(expr instanceof U.AST_Hole)) { if (expr && !(expr instanceof U.AST_Hole)) {
node.start._permute++; node.start._permute++;
CHANGED = true; CHANGED = true;
return expr; return expr instanceof U.AST_Spread ? expr.expression : expr;
} }
} }
else if (node instanceof U.AST_Binary) { else if (node instanceof U.AST_Binary) {
@@ -145,7 +157,9 @@ module.exports = function reduce_test(testcase, minify_options, reduce_options)
return permute < 2 ? expr : wrap_with_console_log(expr); return permute < 2 ? expr : wrap_with_console_log(expr);
} }
else if (node instanceof U.AST_BlockStatement) { else if (node instanceof U.AST_BlockStatement) {
if (in_list) { if (in_list && node.body.filter(function(node) {
return node instanceof U.AST_Const;
}).length == 0) {
node.start._permute++; node.start._permute++;
CHANGED = true; CHANGED = true;
return List.splice(node.body); return List.splice(node.body);
@@ -159,7 +173,13 @@ module.exports = function reduce_test(testcase, minify_options, reduce_options)
][ ((node.start._permute += step) * steps | 0) % 3 ]; ][ ((node.start._permute += step) * steps | 0) % 3 ];
if (expr) { if (expr) {
CHANGED = true; CHANGED = true;
return expr; return expr instanceof U.AST_Spread ? expr.expression : expr;
}
if (node.expression instanceof U.AST_Arrow && node.expression.value) {
var seq = node.args.slice();
seq.push(node.expression.value);
CHANGED = true;
return to_sequence(seq);
} }
if (node.expression instanceof U.AST_Function) { if (node.expression instanceof U.AST_Function) {
// hoist and return expressions from the IIFE function expression // hoist and return expressions from the IIFE function expression
@@ -248,13 +268,23 @@ module.exports = function reduce_test(testcase, minify_options, reduce_options)
} }
} }
else if (node instanceof U.AST_ForIn) { else if (node instanceof U.AST_ForIn) {
var expr = [ var expr;
node.init, switch ((node.start._permute * steps | 0) % 3) {
node.object, case 0:
node.body, if (!(node.init instanceof U.AST_Definitions
][ (node.start._permute * steps | 0) % 3 ]; && node.init.definitions[0].name instanceof U.AST_Destructured)) {
expr = node.init;
}
break;
case 1:
expr = node.object;
break;
case 2:
if (!has_loopcontrol(node.body, node, parent)) expr = node.body;
break;
}
node.start._permute += step; node.start._permute += step;
if (expr && (expr !== node.body || !has_loopcontrol(expr, node, parent))) { if (expr) {
CHANGED = true; CHANGED = true;
return to_statement(expr); return to_statement(expr);
} }
@@ -366,9 +396,8 @@ module.exports = function reduce_test(testcase, minify_options, reduce_options)
} }
if (in_list) { if (in_list) {
// special case to drop object properties and switch branches // drop switch branches
if (parent instanceof U.AST_Object if (parent instanceof U.AST_Switch && parent.expression != node) {
|| parent instanceof U.AST_Switch && parent.expression != node) {
node.start._permute++; node.start._permute++;
CHANGED = true; CHANGED = true;
return List.skip; return List.skip;
@@ -387,6 +416,15 @@ module.exports = function reduce_test(testcase, minify_options, reduce_options)
CHANGED = true; CHANGED = true;
return List.skip; return List.skip;
} }
// skip element/property from (destructured) array/object
if (parent instanceof U.AST_Array
|| parent instanceof U.AST_Destructured
|| parent instanceof U.AST_Object) {
node.start._permute++;
CHANGED = true;
return List.skip;
}
} }
// replace this node // replace this node
@@ -410,7 +448,7 @@ module.exports = function reduce_test(testcase, minify_options, reduce_options)
start: {}, start: {},
}); });
} }
else if (node instanceof U.AST_Var) { else if (node instanceof U.AST_Definitions) {
// remove empty var statement // remove empty var statement
if (node.definitions.length == 0) return in_list ? List.skip : new U.AST_EmptyStatement({ if (node.definitions.length == 0) return in_list ? List.skip : new U.AST_EmptyStatement({
start: {}, start: {},
@@ -427,7 +465,7 @@ module.exports = function reduce_test(testcase, minify_options, reduce_options)
if (node.TYPE == "Call" && node.expression.print_to_string() == "console.log") { if (node.TYPE == "Call" && node.expression.print_to_string() == "console.log") {
return to_sequence(node.args); return to_sequence(node.args);
} }
if (node instanceof U.AST_Catch) { if (node instanceof U.AST_Catch && node.argname instanceof U.AST_SymbolCatch) {
descend(node, this); descend(node, this);
node.body.unshift(new U.AST_SimpleStatement({ node.body.unshift(new U.AST_SimpleStatement({
body: wrap_with_console_log(new U.AST_SymbolRef(node.argname)), body: wrap_with_console_log(new U.AST_SymbolRef(node.argname)),
@@ -436,7 +474,7 @@ module.exports = function reduce_test(testcase, minify_options, reduce_options)
return node; return node;
} }
})); }));
var code = testcase_ast.print_to_string(); var code = testcase_ast.print_to_string(print_options);
var diff = test_for_diff(code, minify_options, result_cache, max_timeout); var diff = test_for_diff(code, minify_options, result_cache, max_timeout);
if (diff && !diff.timed_out && !diff.error) { if (diff && !diff.timed_out && !diff.error) {
testcase = code; testcase = code;
@@ -460,7 +498,7 @@ module.exports = function reduce_test(testcase, minify_options, reduce_options)
var code_ast = testcase_ast.clone(true).transform(tt); var code_ast = testcase_ast.clone(true).transform(tt);
if (!CHANGED) break; if (!CHANGED) break;
try { try {
var code = code_ast.print_to_string(); var code = code_ast.print_to_string(print_options);
} catch (ex) { } catch (ex) {
// AST is not well formed. // AST is not well formed.
// no harm done - just log the error, ignore latest change and continue iterating. // no harm done - just log the error, ignore latest change and continue iterating.
@@ -499,7 +537,28 @@ module.exports = function reduce_test(testcase, minify_options, reduce_options)
log("// reduce test pass " + pass + ": " + testcase.length + " bytes"); log("// reduce test pass " + pass + ": " + testcase.length + " bytes");
} }
} }
testcase = try_beautify(testcase, minify_options, differs.unminified_result, result_cache, max_timeout); var beautified = U.minify(testcase, {
compress: false,
mangle: false,
output: function() {
var options = JSON.parse(JSON.stringify(print_options));
options.beautify = true;
options.braces = true;
options.comments = true;
return options;
}(),
});
testcase = {
code: testcase,
};
if (!beautified.error) {
diff = test_for_diff(beautified.code, minify_options, result_cache, max_timeout);
if (diff && !diff.timed_out && !diff.error) {
testcase = beautified;
testcase.code = "// (beautified)\n" + testcase.code;
differs = diff;
}
}
var lines = [ "" ]; var lines = [ "" ];
if (isNaN(max_timeout)) { if (isNaN(max_timeout)) {
lines.push("// minify error: " + to_comment(strip_color_codes(differs.minified_result.stack))); lines.push("// minify error: " + to_comment(strip_color_codes(differs.minified_result.stack)));
@@ -538,34 +597,6 @@ function trim_trailing_whitespace(value) {
return ("" + value).replace(/\s+$/, ""); return ("" + value).replace(/\s+$/, "");
} }
function try_beautify(testcase, minify_options, expected, result_cache, timeout) {
var result = U.minify(testcase, {
compress: false,
mangle: false,
output: {
beautify: true,
braces: true,
comments: true,
},
});
if (result.error) return {
code: testcase,
};
var toplevel = sandbox.has_toplevel(minify_options);
if (isNaN(timeout)) {
if (!U.minify(result.code, minify_options).error) return {
code: testcase,
};
} else {
var actual = run_code(result.code, toplevel, result_cache, timeout).result;
if (!sandbox.same_stdout(expected, actual)) return {
code: testcase,
};
}
result.code = "// (beautified)\n" + result.code;
return result;
}
function has_exit(fn) { function has_exit(fn) {
var found = false; var found = false;
var tw = new U.TreeWalker(function(node) { var tw = new U.TreeWalker(function(node) {
@@ -600,11 +631,12 @@ function is_error(result) {
} }
function is_timed_out(result) { function is_timed_out(result) {
return is_error(result) && /timed out/.test(result); return is_error(result) && /timed out/.test(result.message);
} }
function is_statement(node) { function is_statement(node) {
return node instanceof U.AST_Statement && !(node instanceof U.AST_Function); return node instanceof U.AST_Statement
&& !(node instanceof U.AST_Arrow || node instanceof U.AST_AsyncFunction || node instanceof U.AST_Function);
} }
function merge_sequence(array, node) { function merge_sequence(array, node) {

View File

@@ -26,17 +26,27 @@ var setupContext = new vm.Script([
]).join("\n")); ]).join("\n"));
function createContext() { function createContext() {
var ctx = vm.createContext(Object.defineProperty({}, "console", { value: { log: log } })); var ctx = vm.createContext(Object.defineProperties({}, {
console: { value: { log: log } },
global: { get: self },
self: { get: self },
window: { get: self },
}));
var global = setupContext.runInContext(ctx); var global = setupContext.runInContext(ctx);
return ctx; return ctx;
function self() {
return this;
}
function safe_log(arg, level) { function safe_log(arg, level) {
if (arg) switch (typeof arg) { if (arg) switch (typeof arg) {
case "function": case "function":
return arg.toString(); return arg.toString();
case "object": case "object":
if (arg === global) return "[object global]"; if (arg === global) return "[object global]";
if (/Error$/.test(arg.name)) return arg.toString(); if (/Error$/.test(arg.name)) return arg.toString();
if (typeof arg.then == "function") return "[object Promise]";
arg.constructor.toString(); arg.constructor.toString();
if (level--) for (var key in arg) { if (level--) for (var key in arg) {
var desc = Object.getOwnPropertyDescriptor(arg, key); var desc = Object.getOwnPropertyDescriptor(arg, key);

File diff suppressed because it is too large Load Diff

View File

@@ -48,8 +48,10 @@ function run() {
stderr = ""; stderr = "";
child.stderr.on("data", trap).pipe(process.stdout); child.stderr.on("data", trap).pipe(process.stdout);
log = setInterval(function() { log = setInterval(function() {
stdout = stdout.replace(/[^\r\n]+\r(?=[^\r\n]+\r)/g, "");
var end = stdout.lastIndexOf("\r"); var end = stdout.lastIndexOf("\r");
console.log(stdout.slice(stdout.lastIndexOf("\r", end - 1) + 1, end)); if (end < 0) return;
console.log(stdout.slice(0, end));
stdout = stdout.slice(end + 1); stdout = stdout.slice(end + 1);
}, 5 * 60 * 1000); }, 5 * 60 * 1000);
} }