-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
CodePrinterTest.java
3492 lines (3068 loc) · 112 KB
/
CodePrinterTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2004 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import static com.google.common.truth.Truth.assertThat;
import static com.google.javascript.jscomp.CompilerTestCase.lines;
import static com.google.javascript.rhino.testing.NodeSubject.assertNode;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import com.google.javascript.jscomp.SourceMap.Format;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public final class CodePrinterTest extends CodePrinterTestBase {
private static final Joiner LINE_JOINER = Joiner.on('\n');
@Test
public void testUnescapedUnicodeLineSeparator_2018() {
languageMode = LanguageMode.ECMASCRIPT_2018;
assertPrintSame("`\u2028`");
assertPrint("'\u2028'", "\"\\u2028\"");
assertPrint("\"\u2028\"", "\"\\u2028\"");
outputCharset = StandardCharsets.UTF_8;
// printed as a unicode escape for ES_2018 output
assertPrint("'\u2028'", "\"\\u2028\"");
assertPrint("\"\u2028\"", "\"\\u2028\"");
}
@Test
public void testUnescapedUnicodeLineSeparator_2019() {
languageMode = LanguageMode.ECMASCRIPT_2019;
assertPrint("'\u2028'", "\"\\u2028\"");
assertPrint("\"\u2028\"", "\"\\u2028\"");
outputCharset = StandardCharsets.UTF_8;
// left unescaped for ES_2019 out
assertPrint("'\u2028'", "\"\u2028\"");
assertPrint("\"\u2028\"", "\"\u2028\"");
}
@Test
public void testUnescapedUnicodeParagraphSeparator_2018() {
languageMode = LanguageMode.ECMASCRIPT_2018;
assertPrintSame("`\u2029`");
assertPrint("'\u2029'", "\"\\u2029\"");
assertPrint("\"\u2029\"", "\"\\u2029\"");
outputCharset = StandardCharsets.UTF_8;
// printed as a unicode escape for ES_2018 output
assertPrint("'\u2029'", "\"\\u2029\"");
assertPrint("\"\u2029\"", "\"\\u2029\"");
}
@Test
public void testUnescapedUnicodeParagraphSeparator_2019() {
languageMode = LanguageMode.ECMASCRIPT_2019;
assertPrint("'\u2029'", "\"\\u2029\"");
assertPrint("\"\u2029\"", "\"\\u2029\"");
outputCharset = StandardCharsets.UTF_8;
// left unescaped for ES_2019 out
assertPrint("'\u2029'", "\"\u2029\"");
assertPrint("\"\u2029\"", "\"\u2029\"");
}
@Test
public void testOptionalCatchBlock() {
useUnsupportedFeatures = true;
assertPrintSame("try{}catch{}");
assertPrintSame("try{}catch{}finally{}");
}
@Test
public void testExponentiationOperator() {
languageMode = LanguageMode.ECMASCRIPT_2016;
assertPrintSame("x**y");
// Exponentiation is right associative
assertPrint("x**(y**z)", "x**y**z");
assertPrintSame("(x**y)**z");
// parens are kept because ExponentiationExpression cannot expand to
// UnaryExpression ** ExponentiationExpression
assertPrintSame("(-x)**y");
// parens are kept because unary operators are higher precedence than '**'
assertPrintSame("-(x**y)");
// parens are not needed for a unary operator on the right operand
assertPrint("x**(-y)", "x**-y");
// NOTE: "-x**y" is a syntax error tested in ParserTest
// ** has a higher precedence than /
assertPrint("x/(y**z)", "x/y**z");
assertPrintSame("(x/y)**z");
}
@Test
public void testExponentiationAssignmentOperator() {
languageMode = LanguageMode.ECMASCRIPT_2016;
assertPrintSame("x**=y");
}
@Test
public void testObjectLiteralWithSpread() {
languageMode = LanguageMode.ECMASCRIPT_NEXT;
assertPrintSame("({...{}})");
assertPrintSame("({...x})");
assertPrintSame("({...x,a:1})");
assertPrintSame("({a:1,...x})");
assertPrintSame("({a:1,...x,b:1})");
assertPrintSame("({...x,...y})");
assertPrintSame("({...x,...f()})");
assertPrintSame("({...{...{}}})");
}
@Test
public void testObjectLiteralWithComma() {
languageMode = LanguageMode.ECMASCRIPT_NEXT;
assertPrintSame("({[(a,b)]:c})");
assertPrintSame("({a:(b,c)})");
assertPrintSame("({[(a,b)]:(c,d)})");
assertPrintSame("({[(a,b)]:c,[d]:(e,f)})");
}
@Test
public void testPrint() {
assertPrint("10 + a + b", "10+a+b");
assertPrint("10 + (30*50)", "10+30*50");
assertPrint("with(x) { x + 3; }", "with(x)x+3");
assertPrint("\"aa'a\"", "\"aa'a\"");
assertPrint("\"aa\\\"a\"", "'aa\"a'");
assertPrint("function foo()\n{return 10;}", "function foo(){return 10}");
assertPrint("a instanceof b", "a instanceof b");
assertPrint("typeof(a)", "typeof a");
assertPrint(
"var foo = x ? { a : 1 } : {a: 3, b:4, \"default\": 5, \"foo-bar\": 6}",
"var foo=x?{a:1}:{a:3,b:4,\"default\":5,\"foo-bar\":6}");
// Safari: needs ';' at the end of a throw statement
assertPrint("function foo(){throw 'error';}",
"function foo(){throw\"error\";}");
// The code printer does not eliminate unnecessary blocks.
assertPrint("var x = 10; { var y = 20; }", "var x=10;{var y=20}");
assertPrint("while (x-- > 0);", "while(x-- >0);");
assertPrint("x-- >> 1", "x-- >>1");
assertPrint("(function () {})(); ",
"(function(){})()");
// Associativity
assertPrint("var a,b,c,d;a || (b&& c) && (a || d)",
"var a,b,c,d;a||b&&c&&(a||d)");
assertPrint("var a,b,c; a || (b || c); a * (b * c); a | (b | c)",
"var a,b,c;a||(b||c);a*(b*c);a|(b|c)");
assertPrint("var a,b,c; a / b / c;a / (b / c); a - (b - c);",
"var a,b,c;a/b/c;a/(b/c);a-(b-c)");
// Nested assignments
assertPrint("var a,b; a = b = 3;",
"var a,b;a=b=3");
assertPrint("var a,b,c,d; a = (b = c = (d = 3));",
"var a,b,c,d;a=b=c=d=3");
assertPrint("var a,b,c; a += (b = c += 3);",
"var a,b,c;a+=b=c+=3");
assertPrint("var a,b,c; a *= (b -= c);",
"var a,b,c;a*=b-=c");
// Precedence
assertPrint("a ? delete b[0] : 3", "a?delete b[0]:3");
assertPrint("(delete a[0])/10", "delete a[0]/10");
// optional '()' for new
// simple new
assertPrint("new A", "new A");
assertPrint("new A()", "new A");
assertPrint("new A('x')", "new A(\"x\")");
// calling instance method directly after new
assertPrint("new A().a()", "(new A).a()");
assertPrint("(new A).a()", "(new A).a()");
// this case should be fixed
assertPrint("new A('y').a()", "(new A(\"y\")).a()");
// internal class
assertPrint("new A.B", "new A.B");
assertPrint("new A.B()", "new A.B");
assertPrint("new A.B('z')", "new A.B(\"z\")");
// calling instance method directly after new internal class
assertPrint("(new A.B).a()", "(new A.B).a()");
assertPrint("new A.B().a()", "(new A.B).a()");
// this case should be fixed
assertPrint("new A.B('w').a()", "(new A.B(\"w\")).a()");
// calling new on the result of a call
assertPrintSame("new (a())");
assertPrint("new (a())()", "new (a())");
assertPrintSame("new (a.b())");
assertPrint("new (a.b())()", "new (a.b())");
// Operators: make sure we don't convert binary + and unary + into ++
assertPrint("x + +y", "x+ +y");
assertPrint("x - (-y)", "x- -y");
assertPrint("x++ +y", "x++ +y");
assertPrint("x-- -y", "x-- -y");
assertPrint("x++ -y", "x++-y");
// Label
assertPrint("foo:for(;;){break foo;}", "foo:for(;;)break foo");
assertPrint("foo:while(1){continue foo;}", "foo:while(1)continue foo");
assertPrintSame("foo:;");
assertPrint("foo: {}", "foo:;");
// Object literals.
assertPrint("({})", "({})");
assertPrint("var x = {};", "var x={}");
assertPrint("({}).x", "({}).x");
assertPrint("({})['x']", "({})[\"x\"]");
assertPrint("({}) instanceof Object", "({})instanceof Object");
assertPrint("({}) || 1", "({})||1");
assertPrint("1 || ({})", "1||{}");
assertPrint("({}) ? 1 : 2", "({})?1:2");
assertPrint("0 ? ({}) : 2", "0?{}:2");
assertPrint("0 ? 1 : ({})", "0?1:{}");
assertPrint("typeof ({})", "typeof{}");
assertPrint("f({})", "f({})");
// Anonymous function expressions.
assertPrint("(function(){})", "(function(){})");
assertPrint("(function(){})()", "(function(){})()");
assertPrint("(function(){})instanceof Object",
"(function(){})instanceof Object");
assertPrint("(function(){}).bind().call()",
"(function(){}).bind().call()");
assertPrint("var x = function() { };", "var x=function(){}");
assertPrint("var x = function() { }();", "var x=function(){}()");
assertPrint("(function() {}), 2", "(function(){}),2");
// Name functions expression.
assertPrint("(function f(){})", "(function f(){})");
// Function declaration.
assertPrint("function f(){}", "function f(){}");
// Make sure we don't treat non-Latin character escapes as raw strings.
assertPrint("({ 'a': 4, '\\u0100': 4 })", "({\"a\":4,\"\\u0100\":4})");
assertPrint("({ a: 4, '\\u0100': 4 })", "({a:4,\"\\u0100\":4})");
// Test if statement and for statements with single statements in body.
assertPrint("if (true) { alert();}", "if(true)alert()");
assertPrint("if (false) {} else {alert(\"a\");}",
"if(false);else alert(\"a\")");
assertPrint("for(;;) { alert();};", "for(;;)alert()");
assertPrint("do { alert(); } while(true);",
"do alert();while(true)");
assertPrint("myLabel: { alert();}",
"myLabel:alert()");
assertPrint("myLabel: for(;;) continue myLabel;",
"myLabel:for(;;)continue myLabel");
// Test nested var statement
assertPrint("if (true) var x; x = 4;", "if(true)var x;x=4");
// Non-latin identifier. Make sure we keep them escaped.
assertPrint("\\u00fb", "\\u00fb");
assertPrint("\\u00fa=1", "\\u00fa=1");
assertPrint("function \\u00f9(){}", "function \\u00f9(){}");
assertPrint("x.\\u00f8", "x.\\u00f8");
assertPrint("x.\\u00f8", "x.\\u00f8");
assertPrint("abc\\u4e00\\u4e01jkl", "abc\\u4e00\\u4e01jkl");
// Test the right-associative unary operators for spurious parens
assertPrint("! ! true", "!!true");
assertPrint("!(!(true))", "!!true");
assertPrint("typeof(void(0))", "typeof void 0");
assertPrint("typeof(void(!0))", "typeof void!0");
assertPrint("+ - + + - + 3", "+-+ +-+3"); // chained unary plus/minus
assertPrint("+(--x)", "+--x");
assertPrint("-(++x)", "-++x");
// needs a space to prevent an ambiguous parse
assertPrint("-(--x)", "- --x");
assertPrint("!(~~5)", "!~~5");
assertPrint("~(a/b)", "~(a/b)");
// Preserve parens to overcome greedy binding of NEW
assertPrint("new (foo.bar()).factory(baz)", "new (foo.bar().factory)(baz)");
assertPrint("new (bar()).factory(baz)", "new (bar().factory)(baz)");
assertPrint("new (new foobar(x)).factory(baz)",
"new (new foobar(x)).factory(baz)");
// Make sure that HOOK is right associative
assertPrint("a ? b : (c ? d : e)", "a?b:c?d:e");
assertPrint("a ? (b ? c : d) : e", "a?b?c:d:e");
assertPrint("(a ? b : c) ? d : e", "(a?b:c)?d:e");
// Test nested ifs
assertPrint("if (x) if (y); else;", "if(x)if(y);else;");
// Test comma.
assertPrint("a,b,c", "a,b,c");
assertPrint("(a,b),c", "a,b,c");
assertPrint("a,(b,c)", "a,b,c");
assertPrint("x=a,b,c", "x=a,b,c");
assertPrint("x=(a,b),c", "x=(a,b),c");
assertPrint("x=a,(b,c)", "x=a,b,c");
assertPrint("x=a,y=b,z=c", "x=a,y=b,z=c");
assertPrint("x=(a,y=b,z=c)", "x=(a,y=b,z=c)");
assertPrint("x=[a,b,c,d]", "x=[a,b,c,d]");
assertPrint("x=[(a,b,c),d]", "x=[(a,b,c),d]");
assertPrint("x=[(a,(b,c)),d]", "x=[(a,b,c),d]");
assertPrint("x=[a,(b,c,d)]", "x=[a,(b,c,d)]");
assertPrint("var x=(a,b)", "var x=(a,b)");
assertPrint("var x=a,b,c", "var x=a,b,c");
assertPrint("var x=(a,b),c", "var x=(a,b),c");
assertPrint("var x=a,b=(c,d)", "var x=a,b=(c,d)");
assertPrint("foo(a,b,c,d)", "foo(a,b,c,d)");
assertPrint("foo((a,b,c),d)", "foo((a,b,c),d)");
assertPrint("foo((a,(b,c)),d)", "foo((a,b,c),d)");
assertPrint("f(a+b,(c,d,(e,f,g)))", "f(a+b,(c,d,e,f,g))");
assertPrint("({}) , 1 , 2", "({}),1,2");
assertPrint("({}) , {} , {}", "({}),{},{}");
assertPrintSame("var a=(b=c,d)");
assertPrintSame("var a=(b[c]=d,e)");
assertPrintSame("var a=(b[c]=d,e[f]=g,h)");
assertPrint("var a = /** @type {?} */ (b=c,d)", "var a=(b=c,d)");
assertPrint("var a = /** @type {?} */ (b[c]=d,e)", "var a=(b[c]=d,e)");
assertPrint("var a = /** @type {?} */ (b[c]=d,e[f]=g,h)", "var a=(b[c]=d,e[f]=g,h)");
// EMPTY nodes
assertPrint("if (x){}", "if(x);");
assertPrint("if(x);", "if(x);");
assertPrint("if(x)if(y);", "if(x)if(y);");
assertPrint("if(x){if(y);}", "if(x)if(y);");
assertPrint("if(x){if(y){};;;}", "if(x)if(y);");
}
@Test
public void testPrintNewVoid() {
// Odd looking but valid. This, of course, will cause a runtime exception but
// should not cause a parse error as "new void 0" would.
assertPrintSame("new (void 0)");
}
@Test
public void testPrintComma1() {
Node node = IR.var(
IR.name("a"),
IR.comma(
IR.comma(
IR.name("b"),
IR.name("c")),
IR.name("d")));
assertPrintNode("var a=(b,c,d)", node);
}
@Test
public void testPrintComma2() {
Node node = IR.var(
IR.name("a"),
IR.comma(
IR.name("b"),
IR.comma(
IR.name("c"),
IR.name("d"))));
assertPrintNode("var a=(b,c,d)", node);
}
@Test
public void testPrintCast1() {
assertPrint("var x = /** @type {number} */ (0);", "var x=0");
assertPrettyPrintSame("var x = /** @type {number} */ (0);\n");
}
@Test
public void testPrintCast2() {
assertPrint("var x = (2+3) * 4;", "var x=(2+3)*4");
assertPrint("var x = /** @type {number} */ (2+3) * 4;", "var x=(2+3)*4");
assertPrettyPrintSame("var x = (/** @type {number} */ (2 + 3)) * 4;\n");
}
@Test
public void testPrintCast3() {
assertPrint("var x = (2*3) + 4;", "var x=2*3+4");
assertPrint("var x = /** @type {number} */ (2*3) + 4;", "var x=2*3+4");
assertPrettyPrintSame("var x = /** @type {number} */ (2 * 3) + 4;\n");
}
@Test
public void testLetConstInIf() {
languageMode = LanguageMode.ECMASCRIPT_NEXT;
assertPrint("if (true) { let x; };", "if(true){let x}");
assertPrint("if (true) { const x = 0; };", "if(true){const x=0}");
}
@Test
public void testPrintBlockScopedFunctions() {
// Safari 3 needs a "{" around a single function
assertPrint("if (true) function foo(){return}",
"if(true){function foo(){return}}");
assertPrint("if(x){;;function y(){};;}", "if(x){function y(){}}");
}
@Test
public void testPrintArrayPatternVar() {
assertPrintSame("var []=[]");
assertPrintSame("var [a]=[1]");
assertPrintSame("var [a,b]=[1,2]");
assertPrintSame("var [a,...b]=[1,2]");
assertPrintSame("var [,b]=[1,2]");
assertPrintSame("var [,,,,,,g]=[1,2,3,4,5,6,7]");
assertPrintSame("var [a,,c]=[1,2,3]");
assertPrintSame("var [a,,,d]=[1,2,3,4]");
assertPrintSame("var [a,,c,,e]=[1,2,3,4,5]");
}
@Test
public void testPrintArrayPatternLet() {
assertPrintSame("let []=[]");
assertPrintSame("let [a]=[1]");
assertPrintSame("let [a,b]=[1,2]");
assertPrintSame("let [a,...b]=[1,2]");
assertPrintSame("let [,b]=[1,2]");
assertPrintSame("let [,,,,,,g]=[1,2,3,4,5,6,7]");
assertPrintSame("let [a,,c]=[1,2,3]");
assertPrintSame("let [a,,,d]=[1,2,3,4]");
assertPrintSame("let [a,,c,,e]=[1,2,3,4,5]");
}
@Test
public void testPrintArrayPatternConst() {
assertPrintSame("const []=[]");
assertPrintSame("const [a]=[1]");
assertPrintSame("const [a,b]=[1,2]");
assertPrintSame("const [a,...b]=[1,2]");
assertPrintSame("const [,b]=[1,2]");
assertPrintSame("const [,,,,,,g]=[1,2,3,4,5,6,7]");
assertPrintSame("const [a,,c]=[1,2,3]");
assertPrintSame("const [a,,,d]=[1,2,3,4]");
assertPrintSame("const [a,,c,,e]=[1,2,3,4,5]");
}
@Test
public void testPrintArrayPatternAssign() {
assertPrintSame("[]=[]");
assertPrintSame("[a]=[1]");
assertPrintSame("[a,b]=[1,2]");
assertPrintSame("[a,...b]=[1,2]");
assertPrintSame("[,b]=[1,2]");
assertPrintSame("[,,,,,,g]=[1,2,3,4,5,6,7]");
assertPrintSame("[a,,c]=[1,2,3]");
assertPrintSame("[a,,,d]=[1,2,3,4]");
assertPrintSame("[a,,c,,e]=[1,2,3,4,5]");
}
@Test
public void testPrintArrayPatternWithInitializer() {
assertPrintSame("[x=1]=[]");
assertPrintSame("[a,,c=2,,e]=[1,2,3,4,5]");
assertPrintSame("[a=1,b=2,c=3]=foo()");
assertPrintSame("[a=(1,2),b]=foo()");
assertPrintSame("[a=[b=(1,2)]=bar(),c]=foo()");
}
@Test
public void testPrintNestedArrayPattern() {
assertPrintSame("var [a,[b,c],d]=[1,[2,3],4]");
assertPrintSame("var [[[[a]]]]=[[[[1]]]]");
assertPrintSame("[a,[b,c],d]=[1,[2,3],4]");
assertPrintSame("[[[[a]]]]=[[[[1]]]]");
}
@Test
public void testPrettyPrintArrayPattern() {
assertPrettyPrint("let [a,b,c]=foo();", "let [a, b, c] = foo();\n");
}
@Test
public void testPrintObjectPatternVar() {
assertPrintSame("var {a}=foo()");
assertPrintSame("var {a,b}=foo()");
assertPrintSame("var {a:a,b:b}=foo()");
}
@Test
public void testPrintObjectPatternLet() {
assertPrintSame("let {a}=foo()");
assertPrintSame("let {a,b}=foo()");
assertPrintSame("let {a:a,b:b}=foo()");
}
@Test
public void testPrintObjectPatternConst() {
assertPrintSame("const {a}=foo()");
assertPrintSame("const {a,b}=foo()");
assertPrintSame("const {a:a,b:b}=foo()");
}
@Test
public void testPrintObjectPatternAssign() {
assertPrintSame("({a}=foo())");
assertPrintSame("({a,b}=foo())");
assertPrintSame("({a:a,b:b}=foo())");
}
@Test
public void testPrintNestedObjectPattern() {
assertPrintSame("({a:{b,c}}=foo())");
assertPrintSame("({a:{b:{c:{d}}}}=foo())");
}
@Test
public void testPrintObjectPatternInitializer() {
assertPrintSame("({a=1}=foo())");
assertPrintSame("({a:{b=2}}=foo())");
assertPrintSame("({a:b=2}=foo())");
assertPrintSame("({a,b:{c=2}}=foo())");
assertPrintSame("({a:{b=2},c}=foo())");
assertPrintSame("({a=(1,2),b}=foo())");
assertPrintSame("({a:b=(1,2),c}=foo())");
}
@Test
public void testPrintObjectPatternWithRest() {
languageMode = LanguageMode.ECMASCRIPT_NEXT;
assertPrintSame("const {a,...rest}=foo()");
assertPrintSame("var {a,...rest}=foo()");
assertPrintSame("let {a,...rest}=foo()");
assertPrintSame("({a,...rest}=foo())");
assertPrintSame("({a=2,...rest}=foo())");
assertPrintSame("({a:b=2,...rest}=foo())");
}
@Test
public void testPrettyPrintObjectPattern() {
assertPrettyPrint("const {a,b,c}=foo();", "const {a, b, c} = foo();\n");
}
@Test
public void testPrintMixedDestructuring() {
assertPrintSame("({a:[b,c]}=foo())");
assertPrintSame("[a,{b,c}]=foo()");
}
@Test
public void testPrintDestructuringInParamList() {
assertPrintSame("function f([a]){}");
assertPrintSame("function f([a,b]){}");
assertPrintSame("function f([a,b]=c()){}");
assertPrintSame("function f([a=(1,2),b=(3,4)]=c()){}");
assertPrintSame("function f({a}){}");
assertPrintSame("function f({a,b}){}");
assertPrintSame("function f({a,b}=c()){}");
assertPrintSame("function f([a,{b,c}]){}");
assertPrintSame("function f({a,b:[c,d]}){}");
}
@Test
public void testPrintDestructuringInRestParam() {
assertPrintSame("function f(...[a,b]){}");
assertPrintSame("function f(...{length:num_params}){}");
}
@Test
public void testDestructuringForInLoops() {
assertPrintSame("for({a}in b)c");
assertPrintSame("for(var {a}in b)c");
assertPrintSame("for(let {a}in b)c");
assertPrintSame("for(const {a}in b)c");
assertPrintSame("for({a:b}in c)d");
assertPrintSame("for(var {a:b}in c)d");
assertPrintSame("for(let {a:b}in c)d");
assertPrintSame("for(const {a:b}in c)d");
assertPrintSame("for([a]in b)c");
assertPrintSame("for(var [a]in b)c");
assertPrintSame("for(let [a]in b)c");
assertPrintSame("for(const [a]in b)c");
}
@Test
public void testDestructuringForOfLoops1() {
assertPrintSame("for({a}of b)c");
assertPrintSame("for(var {a}of b)c");
assertPrintSame("for(let {a}of b)c");
assertPrintSame("for(const {a}of b)c");
assertPrintSame("for({a:b}of c)d");
assertPrintSame("for(var {a:b}of c)d");
assertPrintSame("for(let {a:b}of c)d");
assertPrintSame("for(const {a:b}of c)d");
assertPrintSame("for([a]of b)c");
assertPrintSame("for(var [a]of b)c");
assertPrintSame("for(let [a]of b)c");
assertPrintSame("for(const [a]of b)c");
}
@Test
public void testDestructuringForOfLoops2() {
// The destructuring 'var' statement is a child of the for-of loop, but
// not the first child.
assertPrintSame("for(a of b)var {x}=y");
}
@Test
public void testBreakTrustedStrings() {
// Break scripts
assertPrint("'<script>'", "\"<script>\"");
assertPrint("'</script>'", "\"\\x3c/script>\"");
assertPrint("\"</script> </SCRIPT>\"", "\"\\x3c/script> \\x3c/SCRIPT>\"");
assertPrint("'-->'", "\"--\\x3e\"");
assertPrint("']]>'", "\"]]\\x3e\"");
assertPrint("' --></script>'", "\" --\\x3e\\x3c/script>\"");
assertPrint("/--> <\\/script>/g", "/--\\x3e <\\/script>/g");
// Break HTML start comments. Certain versions of WebKit
// begin an HTML comment when they see this.
assertPrint("'<!-- I am a string -->'",
"\"\\x3c!-- I am a string --\\x3e\"");
assertPrint("'<=&>'", "\"<=&>\"");
}
@Test
public void testBreakUntrustedStrings() {
trustedStrings = false;
// Break scripts
assertPrint("'<script>'", "\"\\x3cscript\\x3e\"");
assertPrint("'</script>'", "\"\\x3c/script\\x3e\"");
assertPrint("\"</script> </SCRIPT>\"", "\"\\x3c/script\\x3e \\x3c/SCRIPT\\x3e\"");
assertPrint("'-->'", "\"--\\x3e\"");
assertPrint("']]>'", "\"]]\\x3e\"");
assertPrint("' --></script>'", "\" --\\x3e\\x3c/script\\x3e\"");
assertPrint("/--> <\\/script>/g", "/--\\x3e <\\/script>/g");
// Break HTML start comments. Certain versions of WebKit
// begin an HTML comment when they see this.
assertPrint("'<!-- I am a string -->'",
"\"\\x3c!-- I am a string --\\x3e\"");
assertPrint("'<=&>'", "\"\\x3c\\x3d\\x26\\x3e\"");
assertPrint("/(?=x)/", "/(?=x)/");
}
@Test
public void testHtmlComments() {
assertPrint("3< !(--x)", "3< !--x");
assertPrint("while (x-- > 0) {}", "while(x-- >0);");
}
@Test
public void testPrintArray() {
assertPrint("[void 0, void 0]", "[void 0,void 0]");
assertPrint("[undefined, undefined]", "[undefined,undefined]");
assertPrint("[ , , , undefined]", "[,,,undefined]");
assertPrint("[ , , , 0]", "[,,,0]");
}
@Test
public void testHook() {
assertPrint("a ? b = 1 : c = 2", "a?b=1:c=2");
assertPrint("x = a ? b = 1 : c = 2", "x=a?b=1:c=2");
assertPrint("(x = a) ? b = 1 : c = 2", "(x=a)?b=1:c=2");
assertPrint("x, a ? b = 1 : c = 2", "x,a?b=1:c=2");
assertPrint("x, (a ? b = 1 : c = 2)", "x,a?b=1:c=2");
assertPrint("(x, a) ? b = 1 : c = 2", "(x,a)?b=1:c=2");
assertPrint("a ? (x, b) : c = 2", "a?(x,b):c=2");
assertPrint("a ? b = 1 : (x,c)", "a?b=1:(x,c)");
assertPrint("a ? b = 1 : c = 2 + x", "a?b=1:c=2+x");
assertPrint("(a ? b = 1 : c = 2) + x", "(a?b=1:c=2)+x");
assertPrint("a ? b = 1 : (c = 2) + x", "a?b=1:(c=2)+x");
assertPrint("a ? (b?1:2) : 3", "a?b?1:2:3");
}
@Test
public void testPrintInOperatorInForLoop() {
// Check for in expression in for's init expression.
// Check alone, with + (higher precedence), with ?: (lower precedence),
// and with conditional.
assertPrint("var a={}; for (var i = (\"length\" in a); i;) {}",
"var a={};for(var i=(\"length\"in a);i;);");
assertPrint("var a={}; for (var i = (\"length\" in a) ? 0 : 1; i;) {}",
"var a={};for(var i=(\"length\"in a)?0:1;i;);");
assertPrint("var a={}; for (var i = (\"length\" in a) + 1; i;) {}",
"var a={};for(var i=(\"length\"in a)+1;i;);");
assertPrint("var a={};for (var i = (\"length\" in a|| \"size\" in a);;);",
"var a={};for(var i=(\"length\"in a)||(\"size\"in a);;);");
assertPrint("var a={};for (var i = (a || a) || (\"size\" in a);;);",
"var a={};for(var i=a||a||(\"size\"in a);;);");
// Test works with unary operators and calls.
assertPrint("var a={}; for (var i = -(\"length\" in a); i;) {}",
"var a={};for(var i=-(\"length\"in a);i;);");
assertPrint("var a={};function b_(p){ return p;};"
+ "for(var i=1,j=b_(\"length\" in a);;) {}",
"var a={};function b_(p){return p}"
+ "for(var i=1,j=b_(\"length\"in a);;);");
// Test we correctly handle an in operator in the test clause.
assertPrint("var a={}; for (;(\"length\" in a);) {}",
"var a={};for(;\"length\"in a;);");
// Test we correctly handle an in operator inside a comma.
assertPrintSame("for(x,(y in z);;)foo()");
assertPrintSame("for(var x,w=(y in z);;)foo()");
// And in operator inside a hook.
assertPrintSame("for(a=c?0:(0 in d);;)foo()");
// And inside an arrow function body
assertPrint(
"var a={}; for(var i = () => (0 in a); i;) {}", "var a={};for(var i=()=>(0 in a);i;);");
assertPrint(
"var a={}; for(var i = () => ({} in a); i;) {}", "var a={};for(var i=()=>({}in a);i;);");
}
@Test
public void testForOf() {
assertPrintSame("for(a of b)c");
assertPrintSame("for(var a of b)c");
}
// In pretty-print mode, make sure there is a space before and after the 'of' in a for/of loop.
@Test
public void testForOfPretty() {
assertPrettyPrintSame("for ([x, y] of b) {\n c;\n}\n");
assertPrettyPrintSame("for (x of [[1, 2]]) {\n c;\n}\n");
assertPrettyPrintSame("for ([x, y] of [[1, 2]]) {\n c;\n}\n");
}
@Test
public void testForAwaitOf() {
languageMode = LanguageMode.ECMASCRIPT_NEXT;
assertPrintSame("for await(a of b)c");
assertPrintSame("for await(var a of b)c");
}
// In pretty-print mode, make sure there is a space before and after the 'of' in a for/of loop.
@Test
public void testForAwaitOfPretty() {
languageMode = LanguageMode.ECMASCRIPT_NEXT;
assertPrettyPrintSame("for await ([x, y] of b) {\n c;\n}\n");
assertPrettyPrintSame("for await (x of [[1, 2]]) {\n c;\n}\n");
assertPrettyPrintSame("for await ([x, y] of [[1, 2]]) {\n c;\n}\n");
}
@Test
public void testLetFor() {
assertPrintSame("for(let a=0;a<5;a++)b");
assertPrintSame("for(let a in b)c");
assertPrintSame("for(let a of b)c");
languageMode = LanguageMode.ECMASCRIPT_NEXT;
assertPrintSame("for await(let a of b)c");
}
@Test
public void testConstFor() {
assertPrintSame("for(const a=5;b<a;b++)c");
assertPrintSame("for(const a in b)c");
assertPrintSame("for(const a of b)c");
languageMode = LanguageMode.ECMASCRIPT_NEXT;
assertPrintSame("for await(const a of b)c");
}
@Test
public void testLiteralProperty() {
assertPrint("(64).toString()", "(64).toString()");
}
// Make sure that the code generator doesn't associate an
// else clause with the wrong if clause.
@Test
public void testAmbiguousElseClauses() {
assertPrintNode("if(x)if(y);else;",
new Node(Token.IF,
Node.newString(Token.NAME, "x"),
new Node(Token.BLOCK,
new Node(Token.IF,
Node.newString(Token.NAME, "y"),
new Node(Token.BLOCK),
// ELSE clause for the inner if
new Node(Token.BLOCK)))));
assertPrintNode("if(x){if(y);}else;",
new Node(Token.IF,
Node.newString(Token.NAME, "x"),
new Node(Token.BLOCK,
new Node(Token.IF,
Node.newString(Token.NAME, "y"),
new Node(Token.BLOCK))),
// ELSE clause for the outer if
new Node(Token.BLOCK)));
assertPrintNode("if(x)if(y);else{if(z);}else;",
new Node(Token.IF,
Node.newString(Token.NAME, "x"),
new Node(Token.BLOCK,
new Node(Token.IF,
Node.newString(Token.NAME, "y"),
new Node(Token.BLOCK),
new Node(Token.BLOCK,
new Node(Token.IF,
Node.newString(Token.NAME, "z"),
new Node(Token.BLOCK))))),
// ELSE clause for the outermost if
new Node(Token.BLOCK)));
}
@Test
public void testLineBreak() {
// line break after function if in a statement context
assertLineBreak("function a() {}\n" +
"function b() {}",
"function a(){}\n" +
"function b(){}\n");
// line break after ; after a function
assertLineBreak("var a = {};\n" +
"a.foo = function () {}\n" +
"function b() {}",
"var a={};a.foo=function(){};\n" +
"function b(){}\n");
// break after comma after a function
assertLineBreak("var a = {\n" +
" b: function() {},\n" +
" c: function() {}\n" +
"};\n" +
"alert(a);",
"var a={b:function(){},\n" +
"c:function(){}};\n" +
"alert(a)");
}
private void assertLineBreak(String js, String expected) {
assertThat(
parsePrint(
js,
newCompilerOptions(
new CompilerOptionBuilder() {
@Override
void setOptions(CompilerOptions options) {
options.setPrettyPrint(false);
options.setLineBreak(true);
options.setLineLengthThreshold(
CompilerOptions.DEFAULT_LINE_LENGTH_THRESHOLD);
}
})))
.isEqualTo(expected);
}
@Test
public void testPreferLineBreakAtEndOfFile() {
// short final line, no previous break, do nothing
assertLineBreakAtEndOfFile(
"\"1234567890\";",
"\"1234567890\"",
"\"1234567890\"");
// short final line, shift previous break to end
assertLineBreakAtEndOfFile(
"\"123456789012345678901234567890\";\"1234567890\"",
"\"123456789012345678901234567890\";\n\"1234567890\"",
"\"123456789012345678901234567890\"; \"1234567890\";\n");
assertLineBreakAtEndOfFile(
"var12345678901234567890123456 instanceof Object;",
"var12345678901234567890123456 instanceof\nObject",
"var12345678901234567890123456 instanceof Object;\n");
// long final line, no previous break, add a break at end
assertLineBreakAtEndOfFile(
"\"1234567890\";\"12345678901234567890\";",
"\"1234567890\";\"12345678901234567890\"",
"\"1234567890\";\"12345678901234567890\";\n");
// long final line, previous break, add a break at end
assertLineBreakAtEndOfFile(
"\"123456789012345678901234567890\";\"12345678901234567890\";",
"\"123456789012345678901234567890\";\n\"12345678901234567890\"",
"\"123456789012345678901234567890\";\n\"12345678901234567890\";\n");
}
private void assertLineBreakAtEndOfFile(String js,
String expectedWithoutBreakAtEnd, String expectedWithBreakAtEnd) {
assertThat(
parsePrint(
js,
newCompilerOptions(
new CompilerOptionBuilder() {
@Override
void setOptions(CompilerOptions options) {
options.setPrettyPrint(false);
options.setLineBreak(false);
options.setLineLengthThreshold(30);
options.setPreferLineBreakAtEndOfFile(false);
}
})))
.isEqualTo(expectedWithoutBreakAtEnd);
assertThat(
parsePrint(
js,
newCompilerOptions(
new CompilerOptionBuilder() {
@Override
void setOptions(CompilerOptions options) {
options.setPrettyPrint(false);
options.setLineBreak(false);
options.setLineLengthThreshold(30);
options.setPreferLineBreakAtEndOfFile(true);
}
})))
.isEqualTo(expectedWithBreakAtEnd);
}
@Test
public void testPrettyPrinter() {
// Ensure that the pretty printer inserts line breaks at appropriate
// places.
assertPrettyPrint("(function(){})();", "(function() {\n})();\n");
assertPrettyPrint("var a = (function() {});alert(a);",
"var a = function() {\n};\nalert(a);\n");
// Check we correctly handle putting brackets around all if clauses so
// we can put breakpoints inside statements.
assertPrettyPrint("if (1) {}",
"if (1) {\n" +
"}\n");
assertPrettyPrint("if (1) {alert(\"\");}",
"if (1) {\n" +
" alert(\"\");\n" +
"}\n");
assertPrettyPrint("if (1)alert(\"\");",
"if (1) {\n" +
" alert(\"\");\n" +
"}\n");
assertPrettyPrint("if (1) {alert();alert();}",
"if (1) {\n" +
" alert();\n" +
" alert();\n" +
"}\n");
// Don't add blocks if they weren't there already.
assertPrettyPrint("label: alert();",
"label: alert();\n");
// But if statements and loops get blocks automagically.
assertPrettyPrint("if (1) alert();",