Debian Codegraph @

test/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntaxTest.java

raw symbols SCIP
1 /*
2 * Copyright 2004 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 /**
20 * Tests for {@link PeepholeSubstituteAlternateSyntax} in isolation.
21 * Tests for the interaction of multiple peephole passes are in
22 * PeepholeIntegrationTest.
23 */
24 public class PeepholeSubstituteAlternateSyntaxTest extends CompilerTestCase {
25
26 // Externs for built-in constructors
27 // Needed for testFoldLiteralObjectConstructors(),
28 // testFoldLiteralArrayConstructors() and testFoldRegExp...()
29 private static final String FOLD_CONSTANTS_TEST_EXTERNS =
30 "var Object = function f(){};\n" +
31 "var RegExp = function f(a){};\n" +
32 "var Array = function f(a){};\n";
33
34 private boolean late = true;
35
36 // TODO(user): Remove this when we no longer need to do string comparison.
37 private PeepholeSubstituteAlternateSyntaxTest(boolean compareAsTree) {
38 super(FOLD_CONSTANTS_TEST_EXTERNS, compareAsTree);
39 }
40
41 public PeepholeSubstituteAlternateSyntaxTest() {
42 super(FOLD_CONSTANTS_TEST_EXTERNS);
43 }
44
45 @Override
46 public void setUp() throws Exception {
47 late = true;
48 super.setUp();
49 enableLineNumberCheck(true);
50 disableNormalize();
51 }
52
53 @Override
54 public CompilerPass getProcessor(final Compiler compiler) {
55 CompilerPass peepholePass =
56 new PeepholeOptimizationsPass(compiler,
57 new PeepholeSubstituteAlternateSyntax(late))
58 .setRetraverseOnChange(false);
59
60 return peepholePass;
61 }
62
63 @Override
64 protected int getNumRepetitions() {
65 return 1;
66 }
67
68 private void foldSame(String js) {
69 testSame(js);
70 }
71
72 private void fold(String js, String expected) {
73 test(js, expected);
74 }
75
76 void assertResultString(String js, String expected) {
77 assertResultString(js, expected, false);
78 }
79
80 // TODO(user): This is same as fold() except it uses string comparison. Any
81 // test that needs tell us where a folding is constructing an invalid AST.
82 void assertResultString(String js, String expected, boolean normalize) {
83 PeepholeSubstituteAlternateSyntaxTest scTest
84 = new PeepholeSubstituteAlternateSyntaxTest(false);
85
86 if (normalize) {
87 scTest.enableNormalize();
88 } else {
89 scTest.disableNormalize();
90 }
91
92 scTest.test(js, expected);
93 }
94
95 /** Check that removing blocks with 1 child works */
96 public void testFoldOneChildBlocks() {
97 late = false;
98 fold("function f(){if(x)a();x=3}",
99 "function f(){x&&a();x=3}");
100 fold("function f(){if(x){a()}x=3}",
101 "function f(){x&&a();x=3}");
102 fold("function f(){if(x){return 3}}",
103 "function f(){if(x)return 3}");
104 fold("function f(){if(x){a()}}",
105 "function f(){x&&a()}");
106 fold("function f(){if(x){throw 1}}", "function f(){if(x)throw 1;}");
107
108 // Try it out with functions
109 fold("function f(){if(x){foo()}}", "function f(){x&&foo()}");
110 fold("function f(){if(x){foo()}else{bar()}}",
111 "function f(){x?foo():bar()}");
112
113 // Try it out with properties and methods
114 fold("function f(){if(x){a.b=1}}", "function f(){if(x)a.b=1}");
115 fold("function f(){if(x){a.b*=1}}", "function f(){x&&(a.b*=1)}");
116 fold("function f(){if(x){a.b+=1}}", "function f(){x&&(a.b+=1)}");
117 fold("function f(){if(x){++a.b}}", "function f(){x&&++a.b}");
118 fold("function f(){if(x){a.foo()}}", "function f(){x&&a.foo()}");
119
120 // Try it out with throw/catch/finally [which should not change]
121 fold("function f(){try{foo()}catch(e){bar(e)}finally{baz()}}",
122 "function f(){try{foo()}catch(e){bar(e)}finally{baz()}}");
123
124 // Try it out with switch statements
125 fold("function f(){switch(x){case 1:break}}",
126 "function f(){switch(x){case 1:break}}");
127
128 // Do while loops stay in a block if that's where they started
129 fold("function f(){if(e1){do foo();while(e2)}else foo2()}",
130 "function f(){if(e1){do foo();while(e2)}else foo2()}");
131 // Test an obscure case with do and while
132 fold("if(x){do{foo()}while(y)}else bar()",
133 "if(x){do foo();while(y)}else bar()");
134
135 // Play with nested IFs
136 fold("function f(){if(x){if(y)foo()}}",
137 "function f(){x&&y&&foo()}");
138 fold("function f(){if(x){if(y)foo();else bar()}}",
139 "function f(){x&&(y?foo():bar())}");
140 fold("function f(){if(x){if(y)foo()}else bar()}",
141 "function f(){x?y&&foo():bar()}");
142 fold("function f(){if(x){if(y)foo();else bar()}else{baz()}}",
143 "function f(){x?y?foo():bar():baz()}");
144
145 fold("if(e1){while(e2){if(e3){foo()}}}else{bar()}",
146 "if(e1)while(e2)e3&&foo();else bar()");
147
148 fold("if(e1){with(e2){if(e3){foo()}}}else{bar()}",
149 "if(e1)with(e2)e3&&foo();else bar()");
150
151 fold("if(a||b){if(c||d){var x;}}", "if(a||b)if(c||d)var x");
152 fold("if(x){ if(y){var x;}else{var z;} }",
153 "if(x)if(y)var x;else var z");
154
155 // NOTE - technically we can remove the blocks since both the parent
156 // and child have elses. But we don't since it causes ambiguities in
157 // some cases where not all descendent ifs having elses
158 fold("if(x){ if(y){var x;}else{var z;} }else{var w}",
159 "if(x)if(y)var x;else var z;else var w");
160 fold("if (x) {var x;}else { if (y) { var y;} }",
161 "if(x)var x;else if(y)var y");
162
163 // Here's some of the ambiguous cases
164 fold("if(a){if(b){f1();f2();}else if(c){f3();}}else {if(d){f4();}}",
165 "if(a)if(b){f1();f2()}else c&&f3();else d&&f4()");
166
167 fold("function f(){foo()}", "function f(){foo()}");
168 fold("switch(x){case y: foo()}", "switch(x){case y:foo()}");
169 fold("try{foo()}catch(ex){bar()}finally{baz()}",
170 "try{foo()}catch(ex){bar()}finally{baz()}");
171 }
172
173 /** Try to minimize returns */
174 public void testFoldReturns() {
175 fold("function f(){if(x)return 1;else return 2}",
176 "function f(){return x?1:2}");
177 fold("function f(){if(x)return 1;return 2}",
178 "function f(){return x?1:2}");
179 fold("function f(){if(x)return;return 2}",
180 "function f(){return x?void 0:2}");
181 fold("function f(){if(x)return 1+x;else return 2-x}",
182 "function f(){return x?1+x:2-x}");
183 fold("function f(){if(x)return 1+x;return 2-x}",
184 "function f(){return x?1+x:2-x}");
185 fold("function f(){if(x)return y += 1;else return y += 2}",
186 "function f(){return x?(y+=1):(y+=2)}");
187
188 fold("function f(){if(x)return;else return 2-x}",
189 "function f(){if(x);else return 2-x}");
190 fold("function f(){if(x)return;return 2-x}",
191 "function f(){return x?void 0:2-x}");
192 fold("function f(){if(x)return x;else return}",
193 "function f(){if(x)return x;{}}");
194 fold("function f(){if(x)return x;return}",
195 "function f(){if(x)return x}");
196
197 foldSame("function f(){for(var x in y) { return x.y; } return k}");
198 }
199
200 public void testCombineIfs1() {
201 fold("function f() {if (x) return 1; if (y) return 1}",
202 "function f() {if (x||y) return 1;}");
203 fold("function f() {if (x) return 1; if (y) foo(); else return 1}",
204 "function f() {if ((!x)&&y) foo(); else return 1;}");
205 }
206
207 public void testCombineIfs2() {
208 // combinable but not yet done
209 foldSame("function f() {if (x) throw 1; if (y) throw 1}");
210 // Can't combine, side-effect
211 fold("function f(){ if (x) g(); if (y) g() }",
212 "function f(){ x&&g(); y&&g() }");
213 // Can't combine, side-effect
214 fold("function f(){ if (x) y = 0; if (y) y = 0; }",
215 "function f(){ x&&(y = 0); y&&(y = 0); }");
216 }
217
218 public void testCombineIfs3() {
219 foldSame("function f() {if (x) return 1; if (y) {g();f()}}");
220 }
221
222
223 /** Try to minimize assignments */
224 public void testFoldAssignments() {
225 fold("function f(){if(x)y=3;else y=4;}", "function f(){y=x?3:4}");
226 fold("function f(){if(x)y=1+a;else y=2+a;}", "function f(){y=x?1+a:2+a}");
227
228 // and operation assignments
229 fold("function f(){if(x)y+=1;else y+=2;}", "function f(){y+=x?1:2}");
230 fold("function f(){if(x)y-=1;else y-=2;}", "function f(){y-=x?1:2}");
231 fold("function f(){if(x)y%=1;else y%=2;}", "function f(){y%=x?1:2}");
232 fold("function f(){if(x)y|=1;else y|=2;}", "function f(){y|=x?1:2}");
233
234 // sanity check, don't fold if the 2 ops don't match
235 foldSame("function f(){x ? y-=1 : y+=2}");
236
237 // sanity check, don't fold if the 2 LHS don't match
238 foldSame("function f(){x ? y-=1 : z-=1}");
239
240 // sanity check, don't fold if there are potential effects
241 foldSame("function f(){x ? y().a=3 : y().a=4}");
242 }
243
244 public void testRemoveDuplicateStatements() {
245 fold("if (a) { x = 1; x++ } else { x = 2; x++ }",
246 "x=(a) ? 1 : 2; x++");
247 fold("if (a) { x = 1; x++; y += 1; z = pi; }" +
248 " else { x = 2; x++; y += 1; z = pi; }",
249 "x=(a) ? 1 : 2; x++; y += 1; z = pi;");
250 fold("function z() {" +
251 "if (a) { foo(); return !0 } else { goo(); return !0 }" +
252 "}",
253 "function z() {(a) ? foo() : goo(); return !0}");
254 fold("function z() {if (a) { foo(); x = true; return true " +
255 "} else { goo(); x = true; return true }}",
256 "function z() {(a) ? foo() : goo(); x = !0; return !0}");
257
258 fold("function z() {" +
259 " if (a) { bar(); foo(); return true }" +
260 " else { bar(); goo(); return true }" +
261 "}",
262 "function z() {" +
263 " if (a) { bar(); foo(); }" +
264 " else { bar(); goo(); }" +
265 " return !0;" +
266 "}");
267 }
268
269 public void testNotCond() {
270 fold("function f(){if(!x)foo()}", "function f(){x||foo()}");
271 fold("function f(){if(!x)b=1}", "function f(){x||(b=1)}");
272 fold("if(!x)z=1;else if(y)z=2", "if(x){y&&(z=2);}else{z=1;}");
273 fold("if(x)y&&(z=2);else z=1;", "x ? y&&(z=2) : z=1");
274 foldSame("function f(){if(!(x=1))a.b=1}");
275 }
276
277 public void testAndParenthesesCount() {
278 fold("function f(){if(x||y)a.foo()}", "function f(){(x||y)&&a.foo()}");
279 fold("function f(){if(x.a)x.a=0}",
280 "function f(){x.a&&(x.a=0)}");
281 foldSame("function f(){if(x()||y()){x()||y()}}");
282 }
283
284 public void testFoldLogicalOpStringCompare() {
285 // side-effects
286 // There is two way to parse two &&'s and both are correct.
287 assertResultString("if(foo() && false) z()", "foo()&&0&&z()");
288 }
289
290 public void testFoldNot() {
291 fold("while(!(x==y)){a=b;}" , "while(x!=y){a=b;}");
292 fold("while(!(x!=y)){a=b;}" , "while(x==y){a=b;}");
293 fold("while(!(x===y)){a=b;}", "while(x!==y){a=b;}");
294 fold("while(!(x!==y)){a=b;}", "while(x===y){a=b;}");
295 // Because !(x<NaN) != x>=NaN don't fold < and > cases.
296 foldSame("while(!(x>y)){a=b;}");
297 foldSame("while(!(x>=y)){a=b;}");
298 foldSame("while(!(x<y)){a=b;}");
299 foldSame("while(!(x<=y)){a=b;}");
300 foldSame("while(!(x<=NaN)){a=b;}");
301
302 // NOT forces a boolean context
303 fold("x = !(y() && true)", "x = !y()");
304 // This will be further optimized by PeepholeFoldConstants.
305 fold("x = !true", "x = !1");
306 }
307
308 public void testFoldRegExpConstructor() {
309 enableNormalize();
310
311 // Cannot fold all the way to a literal because there are too few arguments.
312 fold("x = new RegExp", "x = RegExp()");
313 // Empty regexp should not fold to // since that is a line comment in JS
314 fold("x = new RegExp(\"\")", "x = RegExp(\"\")");
315 fold("x = new RegExp(\"\", \"i\")", "x = RegExp(\"\",\"i\")");
316 // Bogus flags should not fold
317 testSame("x = RegExp(\"foobar\", \"bogus\")",
318 PeepholeSubstituteAlternateSyntax.INVALID_REGULAR_EXPRESSION_FLAGS);
319 // Can Fold
320 fold("x = new RegExp(\"foobar\")", "x = /foobar/");
321 fold("x = RegExp(\"foobar\")", "x = /foobar/");
322 fold("x = new RegExp(\"foobar\", \"i\")", "x = /foobar/i");
323 // Make sure that escaping works
324 fold("x = new RegExp(\"\\\\.\", \"i\")", "x = /\\./i");
325 fold("x = new RegExp(\"/\", \"\")", "x = /\\//");
326 fold("x = new RegExp(\"[/]\", \"\")", "x = /[/]/");
327 fold("x = new RegExp(\"///\", \"\")", "x = /\\/\\/\\//");
328 fold("x = new RegExp(\"\\\\\\/\", \"\")", "x = /\\//");
329 fold("x = new RegExp(\"\\n\")", "x = /\\n/");
330 fold("x = new RegExp('\\\\\\r')", "x = /\\r/");
331
332 // Don't fold really long regexp literals, because Opera 9.2's
333 // regexp parser will explode.
334 String longRegexp = "";
335 for (int i = 0; i < 200; i++) longRegexp += "x";
336 foldSame("x = RegExp(\"" + longRegexp + "\")");
337
338 // Shouldn't fold RegExp unnormalized because
339 // we can't be sure that RegExp hasn't been redefined
340 disableNormalize();
341
342 foldSame("x = new RegExp(\"foobar\")");
343 }
344
345 public void testVersionSpecificRegExpQuirks() {
346 enableNormalize();
347
348 // Don't fold if the flags contain 'g'
349 enableEcmaScript5(false);
350 fold("x = new RegExp(\"foobar\", \"g\")",
351 "x = RegExp(\"foobar\",\"g\")");
352 fold("x = new RegExp(\"foobar\", \"ig\")",
353 "x = RegExp(\"foobar\",\"ig\")");
354 // ... unless in ECMAScript 5 mode per section 7.8.5 of ECMAScript 5.
355 enableEcmaScript5(true);
356 fold("x = new RegExp(\"foobar\", \"ig\")",
357 "x = /foobar/ig");
358 // Don't fold things that crash older versions of Safari and that don't work
359 // as regex literals on other old versions of Safari
360 enableEcmaScript5(false);
361 fold("x = new RegExp(\"\\u2028\")", "x = RegExp(\"\\u2028\")");
362 fold("x = new RegExp(\"\\\\\\\\u2028\")", "x = /\\\\u2028/");
363 // Sunset Safari exclusions for ECMAScript 5 and later.
364 enableEcmaScript5(true);
365 fold("x = new RegExp(\"\\u2028\\u2029\")", "x = /\\u2028\\u2029/");
366 fold("x = new RegExp(\"\\\\u2028\")", "x = /\\u2028/");
367 fold("x = new RegExp(\"\\\\\\\\u2028\")", "x = /\\\\u2028/");
368 }
369
370 public void testFoldRegExpConstructorStringCompare() {
371 // Might have something to do with the internal representation of \n and how
372 // it is used in node comparison.
373 assertResultString("x=new RegExp(\"\\n\", \"i\")", "x=/\\n/i", true);
374 }
375
376 public void testContainsUnicodeEscape() throws Exception {
377 assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(""));
378 assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape("foo"));
379 assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
380 "\u2028"));
381 assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
382 "\\u2028"));
383 assertTrue(
384 PeepholeSubstituteAlternateSyntax.containsUnicodeEscape("foo\\u2028"));
385 assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
386 "foo\\\\u2028"));
387 assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
388 "foo\\\\u2028bar\\u2028"));
389 }
390
391 public void testFoldLiteralObjectConstructors() {
392 enableNormalize();
393
394 // Can fold when normalized
395 fold("x = new Object", "x = ({})");
396 fold("x = new Object()", "x = ({})");
397 fold("x = Object()", "x = ({})");
398
399 disableNormalize();
400 // Cannot fold above when not normalized
401 foldSame("x = new Object");
402 foldSame("x = new Object()");
403 foldSame("x = Object()");
404
405 enableNormalize();
406
407 // Cannot fold, the constructor being used is actually a local function
408 foldSame("x = " +
409 "(function f(){function Object(){this.x=4};return new Object();})();");
410 }
411
412 public void testFoldLiteralArrayConstructors() {
413 enableNormalize();
414
415 // No arguments - can fold when normalized
416 fold("x = new Array", "x = []");
417 fold("x = new Array()", "x = []");
418 fold("x = Array()", "x = []");
419
420 // One argument - can be fold when normalized
421 fold("x = new Array(0)", "x = []");
422 fold("x = Array(0)", "x = []");
423 fold("x = new Array(\"a\")", "x = [\"a\"]");
424 fold("x = Array(\"a\")", "x = [\"a\"]");
425
426 // One argument - cannot be fold when normalized
427 fold("x = new Array(7)", "x = Array(7)");
428 fold("x = Array(7)", "x = Array(7)");
429 fold("x = new Array(y)", "x = Array(y)");
430 fold("x = Array(y)", "x = Array(y)");
431 fold("x = new Array(foo())", "x = Array(foo())");
432 fold("x = Array(foo())", "x = Array(foo())");
433
434 // More than one argument - can be fold when normalized
435 fold("x = new Array(1, 2, 3, 4)", "x = [1, 2, 3, 4]");
436 fold("x = Array(1, 2, 3, 4)", "x = [1, 2, 3, 4]");
437 fold("x = new Array('a', 1, 2, 'bc', 3, {}, 'abc')",
438 "x = ['a', 1, 2, 'bc', 3, {}, 'abc']");
439 fold("x = Array('a', 1, 2, 'bc', 3, {}, 'abc')",
440 "x = ['a', 1, 2, 'bc', 3, {}, 'abc']");
441 fold("x = new Array(Array(1, '2', 3, '4'))", "x = [[1, '2', 3, '4']]");
442 fold("x = Array(Array(1, '2', 3, '4'))", "x = [[1, '2', 3, '4']]");
443 fold("x = new Array(Object(), Array(\"abc\", Object(), Array(Array())))",
444 "x = [{}, [\"abc\", {}, [[]]]]");
445 fold("x = new Array(Object(), Array(\"abc\", Object(), Array(Array())))",
446 "x = [{}, [\"abc\", {}, [[]]]]");
447
448 disableNormalize();
449 // Cannot fold above when not normalized
450 foldSame("x = new Array");
451 foldSame("x = new Array()");
452 foldSame("x = Array()");
453
454 foldSame("x = new Array(0)");
455 foldSame("x = Array(0)");
456 foldSame("x = new Array(\"a\")");
457 foldSame("x = Array(\"a\")");
458 foldSame("x = new Array(7)");
459 foldSame("x = Array(7)");
460 foldSame("x = new Array(foo())");
461 foldSame("x = Array(foo())");
462
463 foldSame("x = new Array(1, 2, 3, 4)");
464 foldSame("x = Array(1, 2, 3, 4)");
465 foldSame("x = new Array('a', 1, 2, 'bc', 3, {}, 'abc')");
466 foldSame("x = Array('a', 1, 2, 'bc', 3, {}, 'abc')");
467 foldSame("x = new Array(Array(1, '2', 3, '4'))");
468 foldSame("x = Array(Array(1, '2', 3, '4'))");
469 foldSame("x = new Array(" +
470 "Object(), Array(\"abc\", Object(), Array(Array())))");
471 foldSame("x = new Array(" +
472 "Object(), Array(\"abc\", Object(), Array(Array())))");
473 }
474
475 public void testMinimizeExprCondition() {
476 fold("(x ? true : false) && y()", "x&&y()");
477 fold("(x ? false : true) && y()", "(!x)&&y()");
478 fold("(x ? true : y) && y()", "(x || y)&&y()");
479 fold("(x ? y : false) && y()", "(x && y)&&y()");
480 fold("(x && true) && y()", "x && y()");
481 fold("(x && false) && y()", "0&&y()");
482 fold("(x || true) && y()", "1&&y()");
483 fold("(x || false) && y()", "x&&y()");
484 }
485
486 public void testMinimizeWhileCondition() {
487 // This test uses constant folding logic, so is only here for completeness.
488 fold("while(!!true) foo()", "while(1) foo()");
489 // These test tryMinimizeCondition
490 fold("while(!!x) foo()", "while(x) foo()");
491 fold("while(!(!x&&!y)) foo()", "while(x||y) foo()");
492 fold("while(x||!!y) foo()", "while(x||y) foo()");
493 fold("while(!(!!x&&y)) foo()", "while(!x||!y) foo()");
494 fold("while(!(!x&&y)) foo()", "while(x||!y) foo()");
495 fold("while(!(x||!y)) foo()", "while(!x&&y) foo()");
496 fold("while(!(x||y)) foo()", "while(!x&&!y) foo()");
497 fold("while(!(!x||y-z)) foo()", "while(x&&!(y-z)) foo()");
498 fold("while(!(!(x/y)||z+w)) foo()", "while(x/y&&!(z+w)) foo()");
499 foldSame("while(!(x+y||z)) foo()");
500 foldSame("while(!(x&&y*z)) foo()");
501 fold("while(!(!!x&&y)) foo()", "while(!x||!y) foo()");
502 fold("while(x&&!0) foo()", "while(x) foo()");
503 fold("while(x||!1) foo()", "while(x) foo()");
504 fold("while(!((x,y)&&z)) foo()", "while(!(x,y)||!z) foo()");
505 }
506
507 public void testMinimizeForCondition() {
508 // This test uses constant folding logic, so is only here for completeness.
509 // These could be simplified to "for(;;) ..."
510 fold("for(;!!true;) foo()", "for(;1;) foo()");
511 // Don't bother with FOR inits as there are normalized out.
512 fold("for(!!true;;) foo()", "for(!0;;) foo()");
513
514 // These test tryMinimizeCondition
515 fold("for(;!!x;) foo()", "for(;x;) foo()");
516
517 // sanity check
518 foldSame("for(a in b) foo()");
519 foldSame("for(a in {}) foo()");
520 foldSame("for(a in []) foo()");
521 fold("for(a in !!true) foo()", "for(a in !0) foo()");
522 }
523
524 public void testMinimizeCondition_example1() {
525 // Based on a real failing code sample.
526 fold("if(!!(f() > 20)) {foo();foo()}", "if(f() > 20){foo();foo()}");
527 }
528
529 public void testFoldLoopBreakLate() {
530 late = true;
531 fold("for(;;) if (a) break", "for(;!a;);");
532 foldSame("for(;;) if (a) { f(); break }");
533 fold("for(;;) if (a) break; else f()", "for(;!a;) { { f(); } }");
534 fold("for(;a;) if (b) break", "for(;a && !b;);");
535 fold("for(;a;) { if (b) break; if (c) break; }",
536 "for(;(a && !b);) if (c) break;");
537 fold("for(;(a && !b);) if (c) break;", "for(;(a && !b) && !c;);");
538
539 // 'while' is normalized to 'for'
540 enableNormalize(true);
541 fold("while(true) if (a) break", "for(;1&&!a;);");
542 }
543
544 public void testFoldLoopBreakEarly() {
545 late = false;
546 foldSame("for(;;) if (a) break");
547 foldSame("for(;;) if (a) { f(); break }");
548 foldSame("for(;;) if (a) break; else f()");
549 foldSame("for(;a;) if (b) break");
550 foldSame("for(;a;) { if (b) break; if (c) break; }");
551
552 foldSame("while(1) if (a) break");
553 enableNormalize(true);
554 foldSame("while(1) if (a) break");
555 }
556
557 public void testFoldConditionalVarDeclaration() {
558 fold("if(x) var y=1;else y=2", "var y=x?1:2");
559 fold("if(x) y=1;else var y=2", "var y=x?1:2");
560
561 foldSame("if(x) var y = 1; z = 2");
562 foldSame("if(x||y) y = 1; var z = 2");
563
564 foldSame("if(x) { var y = 1; print(y)} else y = 2 ");
565 foldSame("if(x) var y = 1; else {y = 2; print(y)}");
566 }
567
568 public void testFoldReturnResult() {
569 fold("function f(){return false;}", "function f(){return !1}");
570 foldSame("function f(){return null;}");
571 fold("function f(){return void 0;}",
572 "function f(){return}");
573 fold("function f(){return;}",
574 "function f(){}");
575 foldSame("function f(){return void foo();}");
576 fold("function f(){return undefined;}",
577 "function f(){return}");
578 fold("function f(){if(a()){return undefined;}}",
579 "function f(){if(a()){return}}");
580 }
581
582 public void testFoldStandardConstructors() {
583 foldSame("new Foo('a')");
584 foldSame("var x = new goog.Foo(1)");
585 foldSame("var x = new String(1)");
586 foldSame("var x = new Number(1)");
587 foldSame("var x = new Boolean(1)");
588
589 enableNormalize();
590
591 fold("var x = new Object('a')", "var x = Object('a')");
592 fold("var x = new RegExp('')", "var x = RegExp('')");
593 fold("var x = new Error('20')", "var x = Error(\"20\")");
594 fold("var x = new Array(20)", "var x = Array(20)");
595 }
596
597 public void testSubsituteReturn() {
598
599 fold("function f() { while(x) { return }}",
600 "function f() { while(x) { break }}");
601
602 foldSame("function f() { while(x) { return 5 } }");
603
604 foldSame("function f() { a: { return 5 } }");
605
606 fold("function f() { while(x) { return 5} return 5}",
607 "function f() { while(x) { break } return 5}");
608
609 fold("function f() { while(x) { return x} return x}",
610 "function f() { while(x) { break } return x}");
611
612 fold("function f() { while(x) { if (y) { return }}}",
613 "function f() { while(x) { if (y) { break }}}");
614
615 fold("function f() { while(x) { if (y) { return }} return}",
616 "function f() { while(x) { if (y) { break }}}");
617
618 fold("function f() { while(x) { if (y) { return 5 }} return 5}",
619 "function f() { while(x) { if (y) { break }} return 5}");
620
621 // It doesn't matter if x is changed between them. We are still returning
622 // x at whatever x value current holds. The whole x = 1 is skipped.
623 fold("function f() { while(x) { if (y) { return x } x = 1} return x}",
624 "function f() { while(x) { if (y) { break } x = 1} return x}");
625
626 // RemoveUnreachableCode would take care of the useless breaks.
627 fold("function f() { while(x) { if (y) { return x } return x} return x}",
628 "function f() { while(x) { if (y) {} break }return x}");
629
630 // A break here only breaks out of the inner loop.
631 foldSame("function f() { while(x) { while (y) { return } } }");
632
633 foldSame("function f() { while(1) { return 7} return 5}");
634
635
636 foldSame("function f() {" +
637 " try { while(x) {return f()}} catch (e) { } return f()}");
638
639 foldSame("function f() {" +
640 " try { while(x) {return f()}} finally {alert(1)} return f()}");
641
642
643 // Both returns has the same handler
644 fold("function f() {" +
645 " try { while(x) { return f() } return f() } catch (e) { } }",
646 "function f() {" +
647 " try { while(x) { break } return f() } catch (e) { } }");
648
649 // We can't fold this because it'll change the order of when foo is called.
650 foldSame("function f() {" +
651 " try { while(x) { return foo() } } finally { alert(1) } " +
652 " return foo()}");
653
654 // This is fine, we have no side effect in the return value.
655 fold("function f() {" +
656 " try { while(x) { return 1 } } finally { alert(1) } return 1}",
657 "function f() {" +
658 " try { while(x) { break } } finally { alert(1) } return 1}"
659 );
660
661 foldSame("function f() { try{ return a } finally { a = 2 } return a; }");
662
663 fold(
664 "function f() { switch(a){ case 1: return a; default: g();} return a;}",
665 "function f() { switch(a){ case 1: break; default: g();} return a; }");
666 }
667
668 public void testSubsituteBreakForThrow() {
669
670 foldSame("function f() { while(x) { throw Error }}");
671
672 fold("function f() { while(x) { throw Error } throw Error }",
673 "function f() { while(x) { break } throw Error}");
674 foldSame("function f() { while(x) { throw Error(1) } throw Error(2)}");
675 foldSame("function f() { while(x) { throw Error(1) } return Error(2)}");
676
677 foldSame("function f() { while(x) { throw 5 } }");
678
679 foldSame("function f() { a: { throw 5 } }");
680
681 fold("function f() { while(x) { throw 5} throw 5}",
682 "function f() { while(x) { break } throw 5}");
683
684 fold("function f() { while(x) { throw x} throw x}",
685 "function f() { while(x) { break } throw x}");
686
687 foldSame("function f() { while(x) { if (y) { throw Error }}}");
688
689 fold("function f() { while(x) { if (y) { throw Error }} throw Error}",
690 "function f() { while(x) { if (y) { break }} throw Error}");
691
692 fold("function f() { while(x) { if (y) { throw 5 }} throw 5}",
693 "function f() { while(x) { if (y) { break }} throw 5}");
694
695 // It doesn't matter if x is changed between them. We are still throwing
696 // x at whatever x value current holds. The whole x = 1 is skipped.
697 fold("function f() { while(x) { if (y) { throw x } x = 1} throw x}",
698 "function f() { while(x) { if (y) { break } x = 1} throw x}");
699
700 // RemoveUnreachableCode would take care of the useless breaks.
701 fold("function f() { while(x) { if (y) { throw x } throw x} throw x}",
702 "function f() { while(x) { if (y) {} break }throw x}");
703
704 // A break here only breaks out of the inner loop.
705 foldSame("function f() { while(x) { while (y) { throw Error } } }");
706
707 foldSame("function f() { while(1) { throw 7} throw 5}");
708
709
710 foldSame("function f() {" +
711 " try { while(x) {throw f()}} catch (e) { } throw f()}");
712
713 foldSame("function f() {" +
714 " try { while(x) {throw f()}} finally {alert(1)} throw f()}");
715
716
717 // Both throws has the same handler
718 fold("function f() {" +
719 " try { while(x) { throw f() } throw f() } catch (e) { } }",
720 "function f() {" +
721 " try { while(x) { break } throw f() } catch (e) { } }");
722
723 // We can't fold this because it'll change the order of when foo is called.
724 foldSame("function f() {" +
725 " try { while(x) { throw foo() } } finally { alert(1) } " +
726 " throw foo()}");
727
728 // This is fine, we have no side effect in the throw value.
729 fold("function f() {" +
730 " try { while(x) { throw 1 } } finally { alert(1) } throw 1}",
731 "function f() {" +
732 " try { while(x) { break } } finally { alert(1) } throw 1}"
733 );
734
735 foldSame("function f() { try{ throw a } finally { a = 2 } throw a; }");
736
737 fold(
738 "function f() { switch(a){ case 1: throw a; default: g();} throw a;}",
739 "function f() { switch(a){ case 1: break; default: g();} throw a; }");
740 }
741
742
743 public void testRemoveDuplicateReturn() {
744 fold("function f() { return; }",
745 "function f(){}");
746 foldSame("function f() { return a; }");
747 fold("function f() { if (x) { return a } return a; }",
748 "function f() { if (x) {} return a; }");
749 foldSame(
750 "function f() { try { if (x) { return a } } catch(e) {} return a; }");
751 foldSame(
752 "function f() { try { if (x) {} } catch(e) {} return 1; }");
753
754 // finally clauses may have side effects
755 foldSame(
756 "function f() { try { if (x) { return a } } finally { a++ } return a; }");
757 // but they don't matter if the result doesn't have side effects and can't
758 // be affect by side-effects.
759 fold("function f() { try { if (x) { return 1 } } finally {} return 1; }",
760 "function f() { try { if (x) {} } finally {} return 1; }");
761
762 fold("function f() { switch(a){ case 1: return a; } return a; }",
763 "function f() { switch(a){ case 1: } return a; }");
764
765 fold("function f() { switch(a){ " +
766 " case 1: return a; case 2: return a; } return a; }",
767 "function f() { switch(a){ " +
768 " case 1: break; case 2: } return a; }");
769 }
770
771 public void testRemoveDuplicateThrow() {
772 foldSame("function f() { throw a; }");
773 fold("function f() { if (x) { throw a } throw a; }",
774 "function f() { if (x) {} throw a; }");
775 foldSame(
776 "function f() { try { if (x) {throw a} } catch(e) {} throw a; }");
777 foldSame(
778 "function f() { try { if (x) {throw 1} } catch(e) {f()} throw 1; }");
779 foldSame(
780 "function f() { try { if (x) {throw 1} } catch(e) {f()} throw 1; }");
781 foldSame(
782 "function f() { try { if (x) {throw 1} } catch(e) {throw 1}}");
783 fold(
784 "function f() { try { if (x) {throw 1} } catch(e) {throw 1} throw 1; }",
785 "function f() { try { if (x) {throw 1} } catch(e) {} throw 1; }");
786
787 // finally clauses may have side effects
788 foldSame(
789 "function f() { try { if (x) { throw a } } finally { a++ } throw a; }");
790 // but they don't matter if the result doesn't have side effects and can't
791 // be affect by side-effects.
792 fold("function f() { try { if (x) { throw 1 } } finally {} throw 1; }",
793 "function f() { try { if (x) {} } finally {} throw 1; }");
794
795 fold("function f() { switch(a){ case 1: throw a; } throw a; }",
796 "function f() { switch(a){ case 1: } throw a; }");
797
798 fold("function f() { switch(a){ " +
799 "case 1: throw a; case 2: throw a; } throw a; }",
800 "function f() { switch(a){ case 1: break; case 2: } throw a; }");
801 }
802
803 public void testNestedIfCombine() {
804 fold("if(x)if(y){while(1){}}", "if(x&&y){while(1){}}");
805 fold("if(x||z)if(y){while(1){}}", "if((x||z)&&y){while(1){}}");
806 fold("if(x)if(y||z){while(1){}}", "if((x)&&(y||z)){while(1){}}");
807 foldSame("if(x||z)if(y||z){while(1){}}");
808 fold("if(x)if(y){if(z){while(1){}}}", "if(x&&y&&z){while(1){}}");
809 }
810
811 public void testFoldTrueFalse() {
812 fold("x = true", "x = !0");
813 fold("x = false", "x = !1");
814 }
815
816 public void testIssue291() {
817 fold("if (true) { f.onchange(); }", "if (1) f.onchange();");
818 foldSame("if (f) { f.onchange(); }");
819 foldSame("if (f) { f.bar(); } else { f.onchange(); }");
820 fold("if (f) { f.bonchange(); }", "f && f.bonchange();");
821 foldSame("if (f) { f['x'](); }");
822 }
823 public void testUndefined() {
824 foldSame("var x = undefined");
825 foldSame("function f(f) {var undefined=2;var x = undefined;}");
826 this.enableNormalize();
827 fold("var x = undefined", "var x=void 0");
828 foldSame(
829 "var undefined = 1;" +
830 "function f() {var undefined=2;var x = undefined;}");
831 foldSame("function f(undefined) {}");
832 foldSame("try {} catch(undefined) {}");
833 foldSame("for (undefined in {}) {}");
834 foldSame("undefined++;");
835 fold("undefined += undefined;", "undefined += void 0;");
836 }
837
838 public void testSplitCommaExpressions() {
839 late = false;
840 // Don't try to split in expressions.
841 foldSame("while (foo(), !0) boo()");
842 foldSame("var a = (foo(), !0);");
843 foldSame("a = (foo(), !0);");
844
845 // Don't try to split COMMA under LABELs.
846 foldSame("a:a(),b()");
847
848 fold("(x=2), foo()", "x=2; foo()");
849 fold("foo(), boo();", "foo(); boo()");
850 fold("(a(), b()), (c(), d());", "a(); b(); (c(), d());");
851 fold("a(); b(); (c(), d());", "a(); b(); c(); d();");
852 fold("foo(), true", "foo();true");
853 fold("foo();true", "foo();1");
854 fold("function x(){foo(), !0}", "function x(){foo(); !0}");
855 fold("function x(){foo(); !0}", "function x(){foo(); 1}");
856 }
857
858 public void testComma1() {
859 late = false;
860 fold("1, 2", "1; 2");
861 fold("1; 2", "1; 1");
862 late = true;
863 foldSame("1, 2");
864 }
865
866 public void testComma2() {
867 late = false;
868 test("1, a()", "1; a()");
869 late = true;
870 foldSame("1, a()");
871 }
872
873 public void testComma3() {
874 late = false;
875 test("1, a(), b()", "1; a(); b()");
876 late = true;
877 foldSame("1, a(), b()");
878 }
879
880 public void testComma4() {
881 late = false;
882 test("a(), b()", "a();b()");
883 late = true;
884 foldSame("a(), b()");
885 }
886
887 public void testComma5() {
888 late = false;
889 test("a(), b(), 1", "a();b();1");
890 late = true;
891 foldSame("a(), b(), 1");
892 }
893
894 public void testObjectLiteral() {
895 test("({})", "1");
896 test("({a:1})", "1");
897 testSame("({a:foo()})");
898 testSame("({'a':foo()})");
899 }
900
901 public void testArrayLiteral() {
902 test("([])", "1");
903 test("([1])", "1");
904 test("([a])", "1");
905 testSame("([foo()])");
906 }
907
908 public void testStringArraySplitting() {
909 testSame("var x=['1','2','3','4']");
910 testSame("var x=['1','2','3','4','5']");
911 test("var x=['1','2','3','4','5','6']",
912 "var x='123456'.split('')");
913 test("var x=['1','2','3','4','5','00']",
914 "var x='1 2 3 4 5 00'.split(' ')");
915 test("var x=['1','2','3','4','5','6','7']",
916 "var x='1234567'.split('')");
917 test("var x=['1','2','3','4','5','6','00']",
918 "var x='1 2 3 4 5 6 00'.split(' ')");
919 test("var x=[' ,',',',',',',',',',',']",
920 "var x=' ,;,;,;,;,;,'.split(';')");
921 test("var x=[',,',' ',',',',',',',',']",
922 "var x=',,; ;,;,;,;,'.split(';')");
923 test("var x=['a,',' ',',',',',',',',']",
924 "var x='a,; ;,;,;,;,'.split(';')");
925
926 // all possible delimiters used, leave it alone
927 testSame("var x=[',', ' ', ';', '{', '}']");
928 }
929
930 public void testRemoveElseCause() {
931 test("function f() {" +
932 " if(x) return 1;" +
933 " else if(x) return 2;" +
934 " else if(x) return 3 }",
935 "function f() {" +
936 " if(x) return 1;" +
937 "{ if(x) return 2;" +
938 "{ if(x) return 3 } } }");
939 }
940
941
942 public void testRemoveElseCause1() {
943 test("function f() { if (x) throw 1; else f() }",
944 "function f() { if (x) throw 1; { f() } }");
945 }
946
947 public void testRemoveElseCause2() {
948 test("function f() { if (x) return 1; else f() }",
949 "function f() { if (x) return 1; { f() } }");
950 test("function f() { if (x) return; else f() }",
951 "function f() { if (x) {} else { f() } }");
952 // This case is handled by minimize exit points.
953 testSame("function f() { if (x) return; f() }");
954 }
955
956 public void testRemoveElseCause3() {
957 testSame("function f() { a:{if (x) break a; else f() } }");
958 testSame("function f() { if (x) { a:{ break a } } else f() }");
959 testSame("function f() { if (x) a:{ break a } else f() }");
960 }
961
962 public void testRemoveElseCause4() {
963 testSame("function f() { if (x) { if (y) { return 1; } } else f() }");
964 }
965
966 public void testIssue925() {
967 test(
968 "if (x[--y] === 1) {\n" +
969 " x[y] = 0;\n" +
970 "} else {\n" +
971 " x[y] = 1;\n" +
972 "}",
973 "(x[--y] === 1) ? x[y] = 0 : x[y] = 1;");
974
975 test(
976 "if (x[--y]) {\n" +
977 " a = 0;\n" +
978 "} else {\n" +
979 " a = 1;\n" +
980 "}",
981 "a = (x[--y]) ? 0 : 1;");
982
983 test("if (x++) { x += 2 } else { x += 3 }",
984 "x++ ? x += 2 : x += 3");
985
986 test("if (x++) { x = x + 2 } else { x = x + 3 }",
987 "x = x++ ? x + 2 : x + 3");
988 }
989
990 public void testBindToCall1() {
991 test("(goog.bind(f))()", "f()");
992 test("(goog.bind(f,a))()", "f.call(a)");
993 test("(goog.bind(f,a,b))()", "f.call(a,b)");
994
995 test("(goog.bind(f))(a)", "f(a)");
996 test("(goog.bind(f,a))(b)", "f.call(a,b)");
997 test("(goog.bind(f,a,b))(c)", "f.call(a,b,c)");
998
999 test("(goog.partial(f))()", "f()");
1000 test("(goog.partial(f,a))()", "f(a)");
1001 test("(goog.partial(f,a,b))()", "f(a,b)");
1002
1003 test("(goog.partial(f))(a)", "f(a)");
1004 test("(goog.partial(f,a))(b)", "f(a,b)");
1005 test("(goog.partial(f,a,b))(c)", "f(a,b,c)");
1006
1007 test("((function(){}).bind())()", "((function(){}))()");
1008 test("((function(){}).bind(a))()", "((function(){})).call(a)");
1009 test("((function(){}).bind(a,b))()", "((function(){})).call(a,b)");
1010
1011 test("((function(){}).bind())(a)", "((function(){}))(a)");
1012 test("((function(){}).bind(a))(b)", "((function(){})).call(a,b)");
1013 test("((function(){}).bind(a,b))(c)", "((function(){})).call(a,b,c)");
1014
1015 // Without using type information we don't know "f" is a function.
1016 testSame("(f.bind())()");
1017 testSame("(f.bind(a))()");
1018 testSame("(f.bind())(a)");
1019 testSame("(f.bind(a))(b)");
1020
1021 // Don't rewrite if the bind isn't the immediate call target
1022 testSame("(goog.bind(f)).call(g)");
1023 }
1024
1025 public void testBindToCall2() {
1026 test("(goog$bind(f))()", "f()");
1027 test("(goog$bind(f,a))()", "f.call(a)");
1028 test("(goog$bind(f,a,b))()", "f.call(a,b)");
1029
1030 test("(goog$bind(f))(a)", "f(a)");
1031 test("(goog$bind(f,a))(b)", "f.call(a,b)");
1032 test("(goog$bind(f,a,b))(c)", "f.call(a,b,c)");
1033
1034 test("(goog$partial(f))()", "f()");
1035 test("(goog$partial(f,a))()", "f(a)");
1036 test("(goog$partial(f,a,b))()", "f(a,b)");
1037
1038 test("(goog$partial(f))(a)", "f(a)");
1039 test("(goog$partial(f,a))(b)", "f(a,b)");
1040 test("(goog$partial(f,a,b))(c)", "f(a,b,c)");
1041
1042 // Don't rewrite if the bind isn't the immediate call target
1043 testSame("(goog$bind(f)).call(g)");
1044 }
1045
1046 public void testBindToCall3() {
1047 // TODO(johnlenz): The code generator wraps free calls with (0,...) to
1048 // prevent leaking "this", but the parser doesn't unfold it, making a
1049 // AST comparison fail. For now do a string comparison to validate the
1050 // correct code is in fact generated.
1051 // The FREE call wrapping should be moved out of the code generator
1052 // and into a denormalizing pass.
1053 new StringCompareTestCase().testBindToCall3();
1054 }
1055
1056 public void testSimpleFunctionCall() {
1057 test("var a = String(23)", "var a = '' + 23");
1058 test("var a = String('hello')", "var a = '' + 'hello'");
1059 testSame("var a = String('hello', bar());");
1060 testSame("var a = String({valueOf: function() { return 1; }});");
1061 }
1062
1063 private static class StringCompareTestCase extends CompilerTestCase {
1064
1065 StringCompareTestCase() {
1066 super("", false);
1067 }
1068
1069 @Override
1070 protected CompilerPass getProcessor(Compiler compiler) {
1071 CompilerPass peepholePass =
1072 new PeepholeOptimizationsPass(compiler,
1073 new PeepholeSubstituteAlternateSyntax(false));
1074 return peepholePass;
1075 }
1076
1077 public void testBindToCall3() {
1078 test("(goog.bind(f.m))()", "(0,f.m)()");
1079 test("(goog.bind(f.m,a))()", "f.m.call(a)");
1080
1081 test("(goog.bind(f.m))(a)", "(0,f.m)(a)");
1082 test("(goog.bind(f.m,a))(b)", "f.m.call(a,b)");
1083
1084 test("(goog.partial(f.m))()", "(0,f.m)()");
1085 test("(goog.partial(f.m,a))()", "(0,f.m)(a)");
1086
1087 test("(goog.partial(f.m))(a)", "(0,f.m)(a)");
1088 test("(goog.partial(f.m,a))(b)", "(0,f.m)(a,b)");
1089
1090 // Without using type information we don't know "f" is a function.
1091 testSame("f.m.bind()()");
1092 testSame("f.m.bind(a)()");
1093 testSame("f.m.bind()(a)");
1094 testSame("f.m.bind(a)(b)");
1095
1096 // Don't rewrite if the bind isn't the immediate call target
1097 testSame("goog.bind(f.m).call(g)");
1098 }
1099 }
1100 }