Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2009 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 import com.google.common.collect.ArrayListMultimap;
20 import com.google.common.collect.ImmutableList;
21 import com.google.common.collect.ImmutableMap;
22 import com.google.common.collect.Lists;
23 import com.google.common.collect.Sets;
24 import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
25 import com.google.javascript.jscomp.CompilerOptions.TracerMode;
26 import com.google.javascript.rhino.Node;
27 import com.google.javascript.rhino.Token;
28
29 import java.io.ByteArrayOutputStream;
30 import java.io.PrintStream;
31 import java.util.List;
32 import java.util.regex.Pattern;
33
34 /**
35 * Tests for {@link PassFactory}.
36 *
37 * @author [email protected] (Nick Santos)
38 */
39 public class IntegrationTest extends IntegrationTestCase {
40
41 private static final String CLOSURE_BOILERPLATE =
42 "/** @define {boolean} */ var COMPILED = false; var goog = {};" +
43 "goog.exportSymbol = function() {};";
44
45 private static final String CLOSURE_COMPILED =
46 "var COMPILED = true; var goog$exportSymbol = function() {};";
47
48 public void testConstructorCycle() {
49 CompilerOptions options = createCompilerOptions();
50 options.checkTypes = true;
51 test(options,
52 "/** @return {function()} */ var AsyncTestCase = function() {};\n" +
53 "/**\n" +
54 " * @constructor\n" +
55 " */ Foo = /** @type {function(new:Foo)} */ (AyncTestCase());",
56 RhinoErrorReporter.PARSE_ERROR);
57 }
58
59 public void testBug1949424() {
60 CompilerOptions options = createCompilerOptions();
61 options.collapseProperties = true;
62 options.closurePass = true;
63 test(options, CLOSURE_BOILERPLATE + "goog.provide('FOO'); FOO.bar = 3;",
64 CLOSURE_COMPILED + "var FOO$bar = 3;");
65 }
66
67 public void testBug1949424_v2() {
68 CompilerOptions options = createCompilerOptions();
69 options.collapseProperties = true;
70 options.closurePass = true;
71 test(options, CLOSURE_BOILERPLATE + "goog.provide('FOO.BAR'); FOO.BAR = 3;",
72 CLOSURE_COMPILED + "var FOO$BAR = 3;");
73 }
74
75 public void testBug1956277() {
76 CompilerOptions options = createCompilerOptions();
77 options.collapseProperties = true;
78 options.inlineVariables = true;
79 test(options, "var CONST = {}; CONST.bar = null;" +
80 "function f(url) { CONST.bar = url; }",
81 "var CONST$bar = null; function f(url) { CONST$bar = url; }");
82 }
83
84 public void testBug1962380() {
85 CompilerOptions options = createCompilerOptions();
86 options.collapseProperties = true;
87 options.inlineVariables = true;
88 options.generateExports = true;
89 test(options,
90 CLOSURE_BOILERPLATE + "/** @export */ goog.CONSTANT = 1;" +
91 "var x = goog.CONSTANT;",
92 "(function() {})('goog.CONSTANT', 1);" +
93 "var x = 1;");
94 }
95
96 public void testBug2410122() {
97 CompilerOptions options = createCompilerOptions();
98 options.generateExports = true;
99 options.closurePass = true;
100 test(options,
101 "var goog = {};" +
102 "function F() {}" +
103 "/** @export */ function G() { goog.base(this); } " +
104 "goog.inherits(G, F);",
105 "var goog = {};" +
106 "function F() {}" +
107 "function G() { F.call(this); } " +
108 "goog.inherits(G, F); goog.exportSymbol('G', G);");
109 }
110
111 public void testIssue90() {
112 CompilerOptions options = createCompilerOptions();
113 options.foldConstants = true;
114 options.inlineVariables = true;
115 options.removeDeadCode = true;
116 test(options,
117 "var x; x && alert(1);",
118 "");
119 }
120
121 public void testClosurePassOff() {
122 CompilerOptions options = createCompilerOptions();
123 options.closurePass = false;
124 testSame(
125 options,
126 "var goog = {}; goog.require = function(x) {}; goog.require('foo');");
127 testSame(
128 options,
129 "var goog = {}; goog.getCssName = function(x) {};" +
130 "goog.getCssName('foo');");
131 }
132
133 public void testClosurePassOn() {
134 CompilerOptions options = createCompilerOptions();
135 options.closurePass = true;
136 test(
137 options,
138 "var goog = {}; goog.require = function(x) {}; goog.require('foo');",
139 ProcessClosurePrimitives.MISSING_PROVIDE_ERROR);
140 test(
141 options,
142 "/** @define {boolean} */ var COMPILED = false;" +
143 "var goog = {}; goog.getCssName = function(x) {};" +
144 "goog.getCssName('foo');",
145 "var COMPILED = true;" +
146 "var goog = {}; goog.getCssName = function(x) {};" +
147 "'foo';");
148 }
149
150 public void testCssNameCheck() {
151 CompilerOptions options = createCompilerOptions();
152 options.closurePass = true;
153 options.checkMissingGetCssNameLevel = CheckLevel.ERROR;
154 options.checkMissingGetCssNameBlacklist = "foo";
155 test(options, "var x = 'foo';",
156 CheckMissingGetCssName.MISSING_GETCSSNAME);
157 }
158
159 public void testBug2592659() {
160 CompilerOptions options = createCompilerOptions();
161 options.closurePass = true;
162 options.checkTypes = true;
163 options.checkMissingGetCssNameLevel = CheckLevel.WARNING;
164 options.checkMissingGetCssNameBlacklist = "foo";
165 test(options,
166 "var goog = {};\n" +
167 "/**\n" +
168 " * @param {string} className\n" +
169 " * @param {string=} opt_modifier\n" +
170 " * @return {string}\n" +
171 "*/\n" +
172 "goog.getCssName = function(className, opt_modifier) {}\n" +
173 "var x = goog.getCssName(123, 'a');",
174 TypeValidator.TYPE_MISMATCH_WARNING);
175 }
176
177 public void testTypedefBeforeOwner1() {
178 CompilerOptions options = createCompilerOptions();
179 options.closurePass = true;
180 test(options,
181 "goog.provide('foo.Bar.Type');\n" +
182 "goog.provide('foo.Bar');\n" +
183 "/** @typedef {number} */ foo.Bar.Type;\n" +
184 "foo.Bar = function() {};",
185 "var foo = {}; foo.Bar.Type; foo.Bar = function() {};");
186 }
187
188 public void testTypedefBeforeOwner2() {
189 CompilerOptions options = createCompilerOptions();
190 options.closurePass = true;
191 options.collapseProperties = true;
192 test(options,
193 "goog.provide('foo.Bar.Type');\n" +
194 "goog.provide('foo.Bar');\n" +
195 "/** @typedef {number} */ foo.Bar.Type;\n" +
196 "foo.Bar = function() {};",
197 "var foo$Bar$Type; var foo$Bar = function() {};");
198 }
199
200 public void testExportedNames() {
201 CompilerOptions options = createCompilerOptions();
202 options.closurePass = true;
203 options.variableRenaming = VariableRenamingPolicy.ALL;
204 test(options,
205 "/** @define {boolean} */ var COMPILED = false;" +
206 "var goog = {}; goog.exportSymbol('b', goog);",
207 "var a = true; var c = {}; c.exportSymbol('b', c);");
208 test(options,
209 "/** @define {boolean} */ var COMPILED = false;" +
210 "var goog = {}; goog.exportSymbol('a', goog);",
211 "var b = true; var c = {}; c.exportSymbol('a', c);");
212 }
213
214 public void testCheckGlobalThisOn() {
215 CompilerOptions options = createCompilerOptions();
216 options.checkSuspiciousCode = true;
217 options.checkGlobalThisLevel = CheckLevel.ERROR;
218 test(options, "function f() { this.y = 3; }", CheckGlobalThis.GLOBAL_THIS);
219 }
220
221 public void testSusiciousCodeOff() {
222 CompilerOptions options = createCompilerOptions();
223 options.checkSuspiciousCode = false;
224 options.checkGlobalThisLevel = CheckLevel.ERROR;
225 test(options, "function f() { this.y = 3; }", CheckGlobalThis.GLOBAL_THIS);
226 }
227
228 public void testCheckGlobalThisOff() {
229 CompilerOptions options = createCompilerOptions();
230 options.checkSuspiciousCode = true;
231 options.checkGlobalThisLevel = CheckLevel.OFF;
232 testSame(options, "function f() { this.y = 3; }");
233 }
234
235 public void testCheckRequiresAndCheckProvidesOff() {
236 testSame(createCompilerOptions(), new String[] {
237 "/** @constructor */ function Foo() {}",
238 "new Foo();"
239 });
240 }
241
242 public void testCheckRequiresOn() {
243 CompilerOptions options = createCompilerOptions();
244 options.checkRequires = CheckLevel.ERROR;
245 test(options, new String[] {
246 "/** @constructor */ function Foo() {}",
247 "new Foo();"
248 }, CheckRequiresForConstructors.MISSING_REQUIRE_WARNING);
249 }
250
251 public void testCheckProvidesOn() {
252 CompilerOptions options = createCompilerOptions();
253 options.checkProvides = CheckLevel.ERROR;
254 test(options, new String[] {
255 "/** @constructor */ function Foo() {}",
256 "new Foo();"
257 }, CheckProvides.MISSING_PROVIDE_WARNING);
258 }
259
260 public void testGenerateExportsOff() {
261 testSame(createCompilerOptions(), "/** @export */ function f() {}");
262 }
263
264 public void testGenerateExportsOn() {
265 CompilerOptions options = createCompilerOptions();
266 options.generateExports = true;
267 test(options, "/** @export */ function f() {}",
268 "/** @export */ function f() {} goog.exportSymbol('f', f);");
269 }
270
271 public void testAngularPassOff() {
272 testSame(createCompilerOptions(),
273 "/** @ngInject */ function f() {} " +
274 "/** @ngInject */ function g(a){} " +
275 "/** @ngInject */ var b = function f(a) {} ");
276 }
277
278 public void testAngularPassOn() {
279 CompilerOptions options = createCompilerOptions();
280 options.angularPass = true;
281 test(options,
282 "/** @ngInject */ function f() {} " +
283 "/** @ngInject */ function g(a){} " +
284 "/** @ngInject */ var b = function f(a, b, c) {} ",
285
286 "function f() {} " +
287 "function g(a) {} g['$inject']=['a'];" +
288 "var b = function f(a, b, c) {}; b['$inject']=['a', 'b', 'c']");
289 }
290
291 public void testExportTestFunctionsOff() {
292 testSame(createCompilerOptions(), "function testFoo() {}");
293 }
294
295 public void testExportTestFunctionsOn() {
296 CompilerOptions options = createCompilerOptions();
297 options.exportTestFunctions = true;
298 test(options, "function testFoo() {}",
299 "/** @export */ function testFoo() {}" +
300 "goog.exportSymbol('testFoo', testFoo);");
301 }
302
303 public void testExpose() {
304 CompilerOptions options = createCompilerOptions();
305 CompilationLevel.ADVANCED_OPTIMIZATIONS
306 .setOptionsForCompilationLevel(options);
307 test(options,
308 "var x = {eeny: 1, /** @expose */ meeny: 2};" +
309 "/** @constructor */ var Foo = function() {};" +
310 "/** @expose */ Foo.prototype.miny = 3;" +
311 "Foo.prototype.moe = 4;" +
312 "/** @expose */ Foo.prototype.tiger;" +
313 "function moe(a, b) { return a.meeny + b.miny + a.tiger; }" +
314 "window['x'] = x;" +
315 "window['Foo'] = Foo;" +
316 "window['moe'] = moe;",
317 "function a(){}" +
318 "a.prototype.miny=3;" +
319 "window.x={a:1,meeny:2};" +
320 "window.Foo=a;" +
321 "window.moe=function(b,c){" +
322 " return b.meeny+c.miny+b.tiger" +
323 "}");
324 }
325
326 public void testCheckSymbolsOff() {
327 CompilerOptions options = createCompilerOptions();
328 testSame(options, "x = 3;");
329 }
330
331 public void testCheckSymbolsOn() {
332 CompilerOptions options = createCompilerOptions();
333 options.checkSymbols = true;
334 test(options, "x = 3;", VarCheck.UNDEFINED_VAR_ERROR);
335 }
336
337 public void testCheckReferencesOff() {
338 CompilerOptions options = createCompilerOptions();
339 testSame(options, "x = 3; var x = 5;");
340 }
341
342 public void testCheckReferencesOn() {
343 CompilerOptions options = createCompilerOptions();
344 options.aggressiveVarCheck = CheckLevel.ERROR;
345 test(options, "x = 3; var x = 5;",
346 VariableReferenceCheck.UNDECLARED_REFERENCE);
347 }
348
349 public void testInferTypes() {
350 CompilerOptions options = createCompilerOptions();
351 options.inferTypes = true;
352 options.checkTypes = false;
353 options.closurePass = true;
354
355 test(options,
356 CLOSURE_BOILERPLATE +
357 "goog.provide('Foo'); /** @enum */ Foo = {a: 3};",
358 TypeCheck.ENUM_NOT_CONSTANT);
359 assertTrue(lastCompiler.getErrorManager().getTypedPercent() == 0);
360
361 // This does not generate a warning.
362 test(options, "/** @type {number} */ var n = window.name;",
363 "var n = window.name;");
364 assertTrue(lastCompiler.getErrorManager().getTypedPercent() == 0);
365 }
366
367 public void testTypeCheckAndInference() {
368 CompilerOptions options = createCompilerOptions();
369 options.checkTypes = true;
370 test(options, "/** @type {number} */ var n = window.name;",
371 TypeValidator.TYPE_MISMATCH_WARNING);
372 assertTrue(lastCompiler.getErrorManager().getTypedPercent() > 0);
373 }
374
375 public void testTypeNameParser() {
376 CompilerOptions options = createCompilerOptions();
377 options.checkTypes = true;
378 test(options, "/** @type {n} */ var n = window.name;",
379 RhinoErrorReporter.TYPE_PARSE_ERROR);
380 }
381
382 // This tests that the TypedScopeCreator is memoized so that it only creates a
383 // Scope object once for each scope. If, when type inference requests a scope,
384 // it creates a new one, then multiple JSType objects end up getting created
385 // for the same local type, and ambiguate will rename the last statement to
386 // o.a(o.a, o.a), which is bad.
387 public void testMemoizedTypedScopeCreator() {
388 CompilerOptions options = createCompilerOptions();
389 options.checkTypes = true;
390 options.ambiguateProperties = true;
391 options.propertyRenaming = PropertyRenamingPolicy.ALL_UNQUOTED;
392 test(options, "function someTest() {\n"
393 + " /** @constructor */\n"
394 + " function Foo() { this.instProp = 3; }\n"
395 + " Foo.prototype.protoProp = function(a, b) {};\n"
396 + " /** @constructor\n @extends Foo */\n"
397 + " function Bar() {}\n"
398 + " goog.inherits(Bar, Foo);\n"
399 + " var o = new Bar();\n"
400 + " o.protoProp(o.protoProp, o.instProp);\n"
401 + "}",
402 "function someTest() {\n"
403 + " function Foo() { this.b = 3; }\n"
404 + " function Bar() {}\n"
405 + " Foo.prototype.a = function(a, b) {};\n"
406 + " goog.c(Bar, Foo);\n"
407 + " var o = new Bar();\n"
408 + " o.a(o.a, o.b);\n"
409 + "}");
410 }
411
412 public void testCheckTypes() {
413 CompilerOptions options = createCompilerOptions();
414 options.checkTypes = true;
415 test(options, "var x = x || {}; x.f = function() {}; x.f(3);",
416 TypeCheck.WRONG_ARGUMENT_COUNT);
417 }
418
419 public void testReplaceCssNames() {
420 CompilerOptions options = createCompilerOptions();
421 options.closurePass = true;
422 options.gatherCssNames = true;
423 test(options, "/** @define {boolean} */\n"
424 + "var COMPILED = false;\n"
425 + "goog.setCssNameMapping({'foo':'bar'});\n"
426 + "function getCss() {\n"
427 + " return goog.getCssName('foo');\n"
428 + "}",
429 "var COMPILED = true;\n"
430 + "function getCss() {\n"
431 + " return \"bar\";"
432 + "}");
433 assertEquals(
434 ImmutableMap.of("foo", new Integer(1)),
435 lastCompiler.getPassConfig().getIntermediateState().cssNames);
436 }
437
438 public void testRemoveClosureAsserts() {
439 CompilerOptions options = createCompilerOptions();
440 options.closurePass = true;
441 testSame(options,
442 "var goog = {};"
443 + "goog.asserts.assert(goog);");
444 options.removeClosureAsserts = true;
445 test(options,
446 "var goog = {};"
447 + "goog.asserts.assert(goog);",
448 "var goog = {};");
449 }
450
451 public void testDeprecation() {
452 String code = "/** @deprecated */ function f() { } function g() { f(); }";
453
454 CompilerOptions options = createCompilerOptions();
455 testSame(options, code);
456
457 options.setWarningLevel(DiagnosticGroups.DEPRECATED, CheckLevel.ERROR);
458 testSame(options, code);
459
460 options.checkTypes = true;
461 test(options, code, CheckAccessControls.DEPRECATED_NAME);
462 }
463
464 public void testVisibility() {
465 String[] code = {
466 "/** @private */ function f() { }",
467 "function g() { f(); }"
468 };
469
470 CompilerOptions options = createCompilerOptions();
471 testSame(options, code);
472
473 options.setWarningLevel(DiagnosticGroups.VISIBILITY, CheckLevel.ERROR);
474 testSame(options, code);
475
476 options.checkTypes = true;
477 test(options, code, CheckAccessControls.BAD_PRIVATE_GLOBAL_ACCESS);
478 }
479
480 public void testUnreachableCode() {
481 String code = "function f() { return \n 3; }";
482
483 CompilerOptions options = createCompilerOptions();
484 testSame(options, code);
485
486 options.checkUnreachableCode = CheckLevel.ERROR;
487 test(options, code, CheckUnreachableCode.UNREACHABLE_CODE);
488 }
489
490 public void testMissingReturn() {
491 String code =
492 "/** @return {number} */ function f() { if (f) { return 3; } }";
493
494 CompilerOptions options = createCompilerOptions();
495 testSame(options, code);
496
497 options.checkMissingReturn = CheckLevel.ERROR;
498 testSame(options, code);
499
500 options.checkTypes = true;
501 test(options, code, CheckMissingReturn.MISSING_RETURN_STATEMENT);
502 }
503
504 public void testIdGenerators() {
505 String code = "function f() {} f('id');";
506
507 CompilerOptions options = createCompilerOptions();
508 testSame(options, code);
509
510 options.idGenerators = Sets.newHashSet("f");
511 test(options, code, "function f() {} 'a';");
512 }
513
514 public void testOptimizeArgumentsArray() {
515 String code = "function f() { return arguments[0]; }";
516
517 CompilerOptions options = createCompilerOptions();
518 testSame(options, code);
519
520 options.optimizeArgumentsArray = true;
521 String argName = "JSCompiler_OptimizeArgumentsArray_p0";
522 test(options, code,
523 "function f(" + argName + ") { return " + argName + "; }");
524 }
525
526 public void testOptimizeParameters() {
527 String code = "function f(a) { return a; } f(true);";
528
529 CompilerOptions options = createCompilerOptions();
530 testSame(options, code);
531
532 options.optimizeParameters = true;
533 test(options, code, "function f() { var a = true; return a;} f();");
534 }
535
536 public void testOptimizeReturns() {
537 String code = "function f(a) { return a; } f(true);";
538
539 CompilerOptions options = createCompilerOptions();
540 testSame(options, code);
541
542 options.optimizeReturns = true;
543 test(options, code, "function f(a) {return;} f(true);");
544 }
545
546 public void testRemoveAbstractMethods() {
547 String code = CLOSURE_BOILERPLATE +
548 "var x = {}; x.foo = goog.abstractMethod; x.bar = 3;";
549
550 CompilerOptions options = createCompilerOptions();
551 testSame(options, code);
552
553 options.closurePass = true;
554 options.collapseProperties = true;
555 test(options, code, CLOSURE_COMPILED + " var x$bar = 3;");
556 }
557
558 public void testCollapseProperties1() {
559 String code =
560 "var x = {}; x.FOO = 5; x.bar = 3;";
561
562 CompilerOptions options = createCompilerOptions();
563 testSame(options, code);
564
565 options.collapseProperties = true;
566 test(options, code, "var x$FOO = 5; var x$bar = 3;");
567 }
568
569 public void testCollapseProperties2() {
570 String code =
571 "var x = {}; x.FOO = 5; x.bar = 3;";
572
573 CompilerOptions options = createCompilerOptions();
574 testSame(options, code);
575
576 options.collapseProperties = true;
577 options.collapseObjectLiterals = true;
578 test(options, code, "var x$FOO = 5; var x$bar = 3;");
579 }
580
581 public void testCollapseObjectLiteral1() {
582 // Verify collapseObjectLiterals does nothing in global scope
583 String code = "var x = {}; x.FOO = 5; x.bar = 3;";
584
585 CompilerOptions options = createCompilerOptions();
586 testSame(options, code);
587
588 options.collapseObjectLiterals = true;
589 testSame(options, code);
590 }
591
592 public void testCollapseObjectLiteral2() {
593 String code =
594 "function f() {var x = {}; x.FOO = 5; x.bar = 3;}";
595
596 CompilerOptions options = createCompilerOptions();
597 testSame(options, code);
598
599 options.collapseObjectLiterals = true;
600 test(options, code,
601 "function f(){" +
602 "var JSCompiler_object_inline_FOO_0;" +
603 "var JSCompiler_object_inline_bar_1;" +
604 "JSCompiler_object_inline_FOO_0=5;" +
605 "JSCompiler_object_inline_bar_1=3}");
606 }
607
608 public void testTightenTypesWithoutTypeCheck() {
609 CompilerOptions options = createCompilerOptions();
610 options.tightenTypes = true;
611 test(options, "", DefaultPassConfig.TIGHTEN_TYPES_WITHOUT_TYPE_CHECK);
612 }
613
614 public void testDisambiguateProperties() {
615 String code =
616 "/** @constructor */ function Foo(){} Foo.prototype.bar = 3;" +
617 "/** @constructor */ function Baz(){} Baz.prototype.bar = 3;";
618
619 CompilerOptions options = createCompilerOptions();
620 testSame(options, code);
621
622 options.disambiguateProperties = true;
623 options.checkTypes = true;
624 test(options, code,
625 "function Foo(){} Foo.prototype.Foo_prototype$bar = 3;" +
626 "function Baz(){} Baz.prototype.Baz_prototype$bar = 3;");
627 }
628
629 public void testMarkPureCalls() {
630 String testCode = "function foo() {} foo();";
631 CompilerOptions options = createCompilerOptions();
632 options.removeDeadCode = true;
633
634 testSame(options, testCode);
635
636 options.computeFunctionSideEffects = true;
637 test(options, testCode, "function foo() {}");
638 }
639
640 public void testMarkNoSideEffects() {
641 String testCode = "noSideEffects();";
642 CompilerOptions options = createCompilerOptions();
643 options.removeDeadCode = true;
644
645 testSame(options, testCode);
646
647 options.markNoSideEffectCalls = true;
648 test(options, testCode, "");
649 }
650
651 public void testChainedCalls() {
652 CompilerOptions options = createCompilerOptions();
653 options.chainCalls = true;
654 test(
655 options,
656 "/** @constructor */ function Foo() {} " +
657 "Foo.prototype.bar = function() { return this; }; " +
658 "var f = new Foo();" +
659 "f.bar(); " +
660 "f.bar(); ",
661 "function Foo() {} " +
662 "Foo.prototype.bar = function() { return this; }; " +
663 "var f = new Foo();" +
664 "f.bar().bar();");
665 }
666
667 public void testExtraAnnotationNames() {
668 CompilerOptions options = createCompilerOptions();
669 options.setExtraAnnotationNames(Sets.newHashSet("TagA", "TagB"));
670 test(
671 options,
672 "/** @TagA */ var f = new Foo(); /** @TagB */ f.bar();",
673 "var f = new Foo(); f.bar();");
674 }
675
676 public void testDevirtualizePrototypeMethods() {
677 CompilerOptions options = createCompilerOptions();
678 options.devirtualizePrototypeMethods = true;
679 test(
680 options,
681 "/** @constructor */ var Foo = function() {}; " +
682 "Foo.prototype.bar = function() {};" +
683 "(new Foo()).bar();",
684 "var Foo = function() {};" +
685 "var JSCompiler_StaticMethods_bar = " +
686 " function(JSCompiler_StaticMethods_bar$self) {};" +
687 "JSCompiler_StaticMethods_bar(new Foo());");
688 }
689
690 public void testCheckConsts() {
691 CompilerOptions options = createCompilerOptions();
692 options.inlineConstantVars = true;
693 test(options, "var FOO = true; FOO = false",
694 ConstCheck.CONST_REASSIGNED_VALUE_ERROR);
695 }
696
697 public void testAllChecksOn() {
698 CompilerOptions options = createCompilerOptions();
699 options.checkSuspiciousCode = true;
700 options.checkControlStructures = true;
701 options.checkRequires = CheckLevel.ERROR;
702 options.checkProvides = CheckLevel.ERROR;
703 options.generateExports = true;
704 options.exportTestFunctions = true;
705 options.closurePass = true;
706 options.checkMissingGetCssNameLevel = CheckLevel.ERROR;
707 options.checkMissingGetCssNameBlacklist = "goog";
708 options.syntheticBlockStartMarker = "synStart";
709 options.syntheticBlockEndMarker = "synEnd";
710 options.checkSymbols = true;
711 options.aggressiveVarCheck = CheckLevel.ERROR;
712 options.processObjectPropertyString = true;
713 options.collapseProperties = true;
714 test(options, CLOSURE_BOILERPLATE, CLOSURE_COMPILED);
715 }
716
717 public void testTypeCheckingWithSyntheticBlocks() {
718 CompilerOptions options = createCompilerOptions();
719 options.syntheticBlockStartMarker = "synStart";
720 options.syntheticBlockEndMarker = "synEnd";
721 options.checkTypes = true;
722
723 // We used to have a bug where the CFG drew an
724 // edge straight from synStart to f(progress).
725 // If that happens, then progress will get type {number|undefined}.
726 testSame(
727 options,
728 "/** @param {number} x */ function f(x) {}" +
729 "function g() {" +
730 " synStart('foo');" +
731 " var progress = 1;" +
732 " f(progress);" +
733 " synEnd('foo');" +
734 "}");
735 }
736
737 public void testCompilerDoesNotBlowUpIfUndefinedSymbols() {
738 CompilerOptions options = createCompilerOptions();
739 options.checkSymbols = true;
740
741 // Disable the undefined variable check.
742 options.setWarningLevel(
743 DiagnosticGroup.forType(VarCheck.UNDEFINED_VAR_ERROR),
744 CheckLevel.OFF);
745
746 // The compiler used to throw an IllegalStateException on this.
747 testSame(options, "var x = {foo: y};");
748 }
749
750 // Make sure that if we change variables which are constant to have
751 // $$constant appended to their names, we remove that tag before
752 // we finish.
753 public void testConstantTagsMustAlwaysBeRemoved() {
754 CompilerOptions options = createCompilerOptions();
755
756 options.variableRenaming = VariableRenamingPolicy.LOCAL;
757 String originalText = "var G_GEO_UNKNOWN_ADDRESS=1;\n" +
758 "function foo() {" +
759 " var localVar = 2;\n" +
760 " if (G_GEO_UNKNOWN_ADDRESS == localVar) {\n" +
761 " alert(\"A\"); }}";
762 String expectedText = "var G_GEO_UNKNOWN_ADDRESS=1;" +
763 "function foo(){var a=2;if(G_GEO_UNKNOWN_ADDRESS==a){alert(\"A\")}}";
764
765 test(options, originalText, expectedText);
766 }
767
768 public void testClosurePassPreservesJsDoc() {
769 CompilerOptions options = createCompilerOptions();
770 options.checkTypes = true;
771 options.closurePass = true;
772
773 test(options,
774 CLOSURE_BOILERPLATE +
775 "goog.provide('Foo'); /** @constructor */ Foo = function() {};" +
776 "var x = new Foo();",
777 "var COMPILED=true;var goog={};goog.exportSymbol=function(){};" +
778 "var Foo=function(){};var x=new Foo");
779 test(options,
780 CLOSURE_BOILERPLATE +
781 "goog.provide('Foo'); /** @enum */ Foo = {a: 3};",
782 TypeCheck.ENUM_NOT_CONSTANT);
783 }
784
785 public void testProvidedNamespaceIsConst() {
786 CompilerOptions options = createCompilerOptions();
787 options.closurePass = true;
788 options.inlineConstantVars = true;
789 options.collapseProperties = true;
790 test(options,
791 "var goog = {}; goog.provide('foo'); " +
792 "function f() { foo = {};}",
793 "var foo = {}; function f() { foo = {}; }",
794 ConstCheck.CONST_REASSIGNED_VALUE_ERROR);
795 }
796
797 public void testProvidedNamespaceIsConst2() {
798 CompilerOptions options = createCompilerOptions();
799 options.closurePass = true;
800 options.inlineConstantVars = true;
801 options.collapseProperties = true;
802 test(options,
803 "var goog = {}; goog.provide('foo.bar'); " +
804 "function f() { foo.bar = {};}",
805 "var foo$bar = {};" +
806 "function f() { foo$bar = {}; }",
807 ConstCheck.CONST_REASSIGNED_VALUE_ERROR);
808 }
809
810 public void testProvidedNamespaceIsConst3() {
811 CompilerOptions options = createCompilerOptions();
812 options.closurePass = true;
813 options.inlineConstantVars = true;
814 options.collapseProperties = true;
815 test(options,
816 "var goog = {}; " +
817 "goog.provide('foo.bar'); goog.provide('foo.bar.baz'); " +
818 "/** @constructor */ foo.bar = function() {};" +
819 "/** @constructor */ foo.bar.baz = function() {};",
820 "var foo$bar = function(){};" +
821 "var foo$bar$baz = function(){};");
822 }
823
824 public void testProvidedNamespaceIsConst4() {
825 CompilerOptions options = createCompilerOptions();
826 options.closurePass = true;
827 options.inlineConstantVars = true;
828 options.collapseProperties = true;
829 test(options,
830 "var goog = {}; goog.provide('foo.Bar'); " +
831 "var foo = {}; foo.Bar = {};",
832 "var foo = {}; foo = {}; foo.Bar = {};");
833 }
834
835 public void testProvidedNamespaceIsConst5() {
836 CompilerOptions options = createCompilerOptions();
837 options.closurePass = true;
838 options.inlineConstantVars = true;
839 options.collapseProperties = true;
840 test(options,
841 "var goog = {}; goog.provide('foo.Bar'); " +
842 "foo = {}; foo.Bar = {};",
843 "var foo = {}; foo = {}; foo.Bar = {};");
844 }
845
846 public void testProcessDefinesAlwaysOn() {
847 test(createCompilerOptions(),
848 "/** @define {boolean} */ var HI = true; HI = false;",
849 "var HI = false;false;");
850 }
851
852 public void testProcessDefinesAdditionalReplacements() {
853 CompilerOptions options = createCompilerOptions();
854 options.setDefineToBooleanLiteral("HI", false);
855 test(options,
856 "/** @define {boolean} */ var HI = true;",
857 "var HI = false;");
858 }
859
860 public void testReplaceMessages() {
861 CompilerOptions options = createCompilerOptions();
862 String prefix = "var goog = {}; goog.getMsg = function() {};";
863 testSame(options, prefix + "var MSG_HI = goog.getMsg('hi');");
864
865 options.messageBundle = new EmptyMessageBundle();
866 test(options,
867 prefix + "/** @desc xyz */ var MSG_HI = goog.getMsg('hi');",
868 prefix + "var MSG_HI = 'hi';");
869 }
870
871 public void testCheckGlobalNames() {
872 CompilerOptions options = createCompilerOptions();
873 options.checkGlobalNamesLevel = CheckLevel.ERROR;
874 test(options, "var x = {}; var y = x.z;",
875 CheckGlobalNames.UNDEFINED_NAME_WARNING);
876 }
877
878 public void testInlineGetters() {
879 CompilerOptions options = createCompilerOptions();
880 String code =
881 "function Foo() {} Foo.prototype.bar = function() { return 3; };" +
882 "var x = new Foo(); x.bar();";
883
884 testSame(options, code);
885 options.inlineGetters = true;
886
887 test(options, code,
888 "function Foo() {} Foo.prototype.bar = function() { return 3 };" +
889 "var x = new Foo(); 3;");
890 }
891
892 public void testInlineGettersWithAmbiguate() {
893 CompilerOptions options = createCompilerOptions();
894
895 String code =
896 "/** @constructor */" +
897 "function Foo() {}" +
898 "/** @type {number} */ Foo.prototype.field;" +
899 "Foo.prototype.getField = function() { return this.field; };" +
900 "/** @constructor */" +
901 "function Bar() {}" +
902 "/** @type {string} */ Bar.prototype.field;" +
903 "Bar.prototype.getField = function() { return this.field; };" +
904 "new Foo().getField();" +
905 "new Bar().getField();";
906
907 testSame(options, code);
908
909 options.inlineGetters = true;
910
911 test(options, code,
912 "function Foo() {}" +
913 "Foo.prototype.field;" +
914 "Foo.prototype.getField = function() { return this.field; };" +
915 "function Bar() {}" +
916 "Bar.prototype.field;" +
917 "Bar.prototype.getField = function() { return this.field; };" +
918 "new Foo().field;" +
919 "new Bar().field;");
920
921 options.checkTypes = true;
922 options.ambiguateProperties = true;
923
924 // Propagating the wrong type information may cause ambiguate properties
925 // to generate bad code.
926 testSame(options, code);
927 }
928
929 public void testInlineVariables() {
930 CompilerOptions options = createCompilerOptions();
931 String code = "function foo() {} var x = 3; foo(x);";
932 testSame(options, code);
933
934 options.inlineVariables = true;
935 test(options, code, "(function foo() {})(3);");
936
937 options.propertyRenaming = PropertyRenamingPolicy.HEURISTIC;
938 test(options, code, DefaultPassConfig.CANNOT_USE_PROTOTYPE_AND_VAR);
939 }
940
941 public void testInlineConstants() {
942 CompilerOptions options = createCompilerOptions();
943 String code = "function foo() {} var x = 3; foo(x); var YYY = 4; foo(YYY);";
944 testSame(options, code);
945
946 options.inlineConstantVars = true;
947 test(options, code, "function foo() {} var x = 3; foo(x); foo(4);");
948 }
949
950 public void testMinimizeExits() {
951 CompilerOptions options = createCompilerOptions();
952 String code =
953 "function f() {" +
954 " if (window.foo) return; window.h(); " +
955 "}";
956 testSame(options, code);
957
958 options.foldConstants = true;
959 test(
960 options, code,
961 "function f() {" +
962 " window.foo || window.h(); " +
963 "}");
964 }
965
966 public void testFoldConstants() {
967 CompilerOptions options = createCompilerOptions();
968 String code = "if (true) { window.foo(); }";
969 testSame(options, code);
970
971 options.foldConstants = true;
972 test(options, code, "window.foo();");
973 }
974
975 public void testRemoveUnreachableCode() {
976 CompilerOptions options = createCompilerOptions();
977 String code = "function f() { return; f(); }";
978 testSame(options, code);
979
980 options.removeDeadCode = true;
981 test(options, code, "function f() {}");
982 }
983
984 public void testRemoveUnusedPrototypeProperties1() {
985 CompilerOptions options = createCompilerOptions();
986 String code = "function Foo() {} " +
987 "Foo.prototype.bar = function() { return new Foo(); };";
988 testSame(options, code);
989
990 options.removeUnusedPrototypeProperties = true;
991 test(options, code, "function Foo() {}");
992 }
993
994 public void testRemoveUnusedPrototypeProperties2() {
995 CompilerOptions options = createCompilerOptions();
996 String code = "function Foo() {} " +
997 "Foo.prototype.bar = function() { return new Foo(); };" +
998 "function f(x) { x.bar(); }";
999 testSame(options, code);
1000
1001 options.removeUnusedPrototypeProperties = true;
1002 testSame(options, code);
1003
1004 options.removeUnusedVars = true;
1005 test(options, code, "");
1006 }
1007
1008 public void testSmartNamePass() {
1009 CompilerOptions options = createCompilerOptions();
1010 String code = "function Foo() { this.bar(); } " +
1011 "Foo.prototype.bar = function() { return Foo(); };";
1012 testSame(options, code);
1013
1014 options.smartNameRemoval = true;
1015 test(options, code, "");
1016 }
1017
1018 public void testDeadAssignmentsElimination() {
1019 CompilerOptions options = createCompilerOptions();
1020 String code = "function f() { var x = 3; 4; x = 5; return x; } f(); ";
1021 testSame(options, code);
1022
1023 options.deadAssignmentElimination = true;
1024 testSame(options, code);
1025
1026 options.removeUnusedVars = true;
1027 test(options, code, "function f() { var x = 3; 4; x = 5; return x; } f();");
1028 }
1029
1030 public void testInlineFunctions() {
1031 CompilerOptions options = createCompilerOptions();
1032 String code = "function f() { return 3; } f(); ";
1033 testSame(options, code);
1034
1035 options.inlineFunctions = true;
1036 test(options, code, "3;");
1037 }
1038
1039 public void testRemoveUnusedVars1() {
1040 CompilerOptions options = createCompilerOptions();
1041 String code = "function f(x) {} f();";
1042 testSame(options, code);
1043
1044 options.removeUnusedVars = true;
1045 test(options, code, "function f() {} f();");
1046 }
1047
1048 public void testRemoveUnusedVars2() {
1049 CompilerOptions options = createCompilerOptions();
1050 String code = "(function f(x) {})();var g = function() {}; g();";
1051 testSame(options, code);
1052
1053 options.removeUnusedVars = true;
1054 test(options, code, "(function() {})();var g = function() {}; g();");
1055
1056 options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.UNMAPPED;
1057 test(options, code, "(function f() {})();var g = function $g$() {}; g();");
1058 }
1059
1060 public void testCrossModuleCodeMotion() {
1061 CompilerOptions options = createCompilerOptions();
1062 String[] code = new String[] {
1063 "var x = 1;",
1064 "x;",
1065 };
1066 testSame(options, code);
1067
1068 options.crossModuleCodeMotion = true;
1069 test(options, code, new String[] {
1070 "",
1071 "var x = 1; x;",
1072 });
1073 }
1074
1075 public void testCrossModuleMethodMotion() {
1076 CompilerOptions options = createCompilerOptions();
1077 String[] code = new String[] {
1078 "var Foo = function() {}; Foo.prototype.bar = function() {};" +
1079 "var x = new Foo();",
1080 "x.bar();",
1081 };
1082 testSame(options, code);
1083
1084 options.crossModuleMethodMotion = true;
1085 test(options, code, new String[] {
1086 CrossModuleMethodMotion.STUB_DECLARATIONS +
1087 "var Foo = function() {};" +
1088 "Foo.prototype.bar=JSCompiler_stubMethod(0); var x=new Foo;",
1089 "Foo.prototype.bar=JSCompiler_unstubMethod(0,function(){}); x.bar()",
1090 });
1091 }
1092
1093 public void testFlowSensitiveInlineVariables1() {
1094 CompilerOptions options = createCompilerOptions();
1095 String code = "function f() { var x = 3; x = 5; return x; }";
1096 testSame(options, code);
1097
1098 options.flowSensitiveInlineVariables = true;
1099 test(options, code, "function f() { var x = 3; return 5; }");
1100
1101 String unusedVar = "function f() { var x; x = 5; return x; } f()";
1102 test(options, unusedVar, "function f() { var x; return 5; } f()");
1103
1104 options.removeUnusedVars = true;
1105 test(options, unusedVar, "function f() { return 5; } f()");
1106 }
1107
1108 public void testFlowSensitiveInlineVariables2() {
1109 CompilerOptions options = createCompilerOptions();
1110 CompilationLevel.SIMPLE_OPTIMIZATIONS
1111 .setOptionsForCompilationLevel(options);
1112 test(options,
1113 "function f () {\n" +
1114 " var ab = 0;\n" +
1115 " ab += '-';\n" +
1116 " alert(ab);\n" +
1117 "}",
1118 "function f () {\n" +
1119 " alert('0-');\n" +
1120 "}");
1121 }
1122
1123 public void testCollapseAnonymousFunctions() {
1124 CompilerOptions options = createCompilerOptions();
1125 String code = "var f = function() {};";
1126 testSame(options, code);
1127
1128 options.collapseAnonymousFunctions = true;
1129 test(options, code, "function f() {}");
1130 }
1131
1132 public void testMoveFunctionDeclarations() {
1133 CompilerOptions options = createCompilerOptions();
1134 String code = "var x = f(); function f() { return 3; }";
1135 testSame(options, code);
1136
1137 options.moveFunctionDeclarations = true;
1138 test(options, code, "function f() { return 3; } var x = f();");
1139 }
1140
1141 public void testNameAnonymousFunctions() {
1142 CompilerOptions options = createCompilerOptions();
1143 String code = "var f = function() {};";
1144 testSame(options, code);
1145
1146 options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.MAPPED;
1147 test(options, code, "var f = function $() {}");
1148 assertNotNull(lastCompiler.getResult().namedAnonFunctionMap);
1149
1150 options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.UNMAPPED;
1151 test(options, code, "var f = function $f$() {}");
1152 assertNull(lastCompiler.getResult().namedAnonFunctionMap);
1153 }
1154
1155 public void testNameAnonymousFunctionsWithVarRemoval() {
1156 CompilerOptions options = createCompilerOptions();
1157 options.setRemoveUnusedVariables(CompilerOptions.Reach.LOCAL_ONLY);
1158 options.setInlineVariables(true);
1159 String code = "var f = function longName() {}; var g = function() {};" +
1160 "function longerName() {} var i = longerName;";
1161 test(options, code,
1162 "var f = function() {}; var g = function() {}; " +
1163 "var i = function() {};");
1164
1165 options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.MAPPED;
1166 test(options, code,
1167 "var f = function longName() {}; var g = function $() {};" +
1168 "var i = function longerName(){};");
1169 assertNotNull(lastCompiler.getResult().namedAnonFunctionMap);
1170
1171 options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.UNMAPPED;
1172 test(options, code,
1173 "var f = function longName() {}; var g = function $g$() {};" +
1174 "var i = function longerName(){};");
1175 assertNull(lastCompiler.getResult().namedAnonFunctionMap);
1176 }
1177
1178 public void testExtractPrototypeMemberDeclarations() {
1179 CompilerOptions options = createCompilerOptions();
1180 String code = "var f = function() {};";
1181 String expected = "var a; var b = function() {}; a = b.prototype;";
1182 for (int i = 0; i < 10; i++) {
1183 code += "f.prototype.a = " + i + ";";
1184 expected += "a.a = " + i + ";";
1185 }
1186 testSame(options, code);
1187
1188 options.extractPrototypeMemberDeclarations = true;
1189 options.variableRenaming = VariableRenamingPolicy.ALL;
1190 test(options, code, expected);
1191
1192 options.propertyRenaming = PropertyRenamingPolicy.HEURISTIC;
1193 options.variableRenaming = VariableRenamingPolicy.OFF;
1194 testSame(options, code);
1195 }
1196
1197 public void testDevirtualizationAndExtractPrototypeMemberDeclarations() {
1198 CompilerOptions options = createCompilerOptions();
1199 options.devirtualizePrototypeMethods = true;
1200 options.collapseAnonymousFunctions = true;
1201 options.extractPrototypeMemberDeclarations = true;
1202 options.variableRenaming = VariableRenamingPolicy.ALL;
1203 String code = "var f = function() {};";
1204 String expected = "var a; function b() {} a = b.prototype;";
1205 for (int i = 0; i < 10; i++) {
1206 code += "f.prototype.argz = function() {arguments};";
1207 code += "f.prototype.devir" + i + " = function() {};";
1208
1209 char letter = (char) ('d' + i);
1210
1211 // skip i,j,o (reserved)
1212 if (letter >= 'i') letter++;
1213 if (letter >= 'j') letter++;
1214 if (letter >= 'o') letter++;
1215
1216 expected += "a.argz = function() {arguments};";
1217 expected += "function " + letter + "(c){}";
1218 }
1219
1220 code += "var F = new f(); F.argz();";
1221 expected += "var q = new b(); q.argz();";
1222
1223 for (int i = 0; i < 10; i++) {
1224 code += "F.devir" + i + "();";
1225
1226 char letter = (char) ('d' + i);
1227
1228 // skip i,j,o (reserved)
1229 if (letter >= 'i') letter++;
1230 if (letter >= 'j') letter++;
1231 if (letter >= 'o') letter++;
1232
1233 expected += letter + "(q);";
1234 }
1235 test(options, code, expected);
1236 }
1237
1238 public void testCoalesceVariableNames() {
1239 CompilerOptions options = createCompilerOptions();
1240 String code = "function f() {var x = 3; var y = x; var z = y; return z;}";
1241 testSame(options, code);
1242
1243 options.coalesceVariableNames = true;
1244 test(options, code,
1245 "function f() {var x = 3; x = x; x = x; return x;}");
1246 }
1247
1248 public void testPropertyRenaming() {
1249 CompilerOptions options = createCompilerOptions();
1250 options.propertyAffinity = true;
1251 String code =
1252 "function f() { return this.foo + this['bar'] + this.Baz; }" +
1253 "f.prototype.bar = 3; f.prototype.Baz = 3;";
1254 String heuristic =
1255 "function f() { return this.foo + this['bar'] + this.a; }" +
1256 "f.prototype.bar = 3; f.prototype.a = 3;";
1257 String aggHeuristic =
1258 "function f() { return this.foo + this['b'] + this.a; } " +
1259 "f.prototype.b = 3; f.prototype.a = 3;";
1260 String all =
1261 "function f() { return this.b + this['bar'] + this.a; }" +
1262 "f.prototype.c = 3; f.prototype.a = 3;";
1263 testSame(options, code);
1264
1265 options.propertyRenaming = PropertyRenamingPolicy.HEURISTIC;
1266 test(options, code, heuristic);
1267
1268 options.propertyRenaming = PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC;
1269 test(options, code, aggHeuristic);
1270
1271 options.propertyRenaming = PropertyRenamingPolicy.ALL_UNQUOTED;
1272 test(options, code, all);
1273 }
1274
1275 public void testConvertToDottedProperties() {
1276 CompilerOptions options = createCompilerOptions();
1277 String code =
1278 "function f() { return this['bar']; } f.prototype.bar = 3;";
1279 String expected =
1280 "function f() { return this.bar; } f.prototype.a = 3;";
1281 testSame(options, code);
1282
1283 options.convertToDottedProperties = true;
1284 options.propertyRenaming = PropertyRenamingPolicy.ALL_UNQUOTED;
1285 test(options, code, expected);
1286 }
1287
1288 public void testRewriteFunctionExpressions() {
1289 CompilerOptions options = createCompilerOptions();
1290 String code = "var a = function() {};";
1291 String expected = "function JSCompiler_emptyFn(){return function(){}} " +
1292 "var a = JSCompiler_emptyFn();";
1293 for (int i = 0; i < 10; i++) {
1294 code += "a = function() {};";
1295 expected += "a = JSCompiler_emptyFn();";
1296 }
1297 testSame(options, code);
1298
1299 options.rewriteFunctionExpressions = true;
1300 test(options, code, expected);
1301 }
1302
1303 public void testAliasAllStrings() {
1304 CompilerOptions options = createCompilerOptions();
1305 String code = "function f() { return 'a'; }";
1306 String expected = "var $$S_a = 'a'; function f() { return $$S_a; }";
1307 testSame(options, code);
1308
1309 options.aliasAllStrings = true;
1310 test(options, code, expected);
1311 }
1312
1313 public void testAliasExterns() {
1314 CompilerOptions options = createCompilerOptions();
1315 String code = "function f() { return window + window + window + window; }";
1316 String expected = "var GLOBAL_window = window;" +
1317 "function f() { return GLOBAL_window + GLOBAL_window + " +
1318 " GLOBAL_window + GLOBAL_window; }";
1319 testSame(options, code);
1320
1321 options.aliasExternals = true;
1322 test(options, code, expected);
1323 }
1324
1325 public void testAliasKeywords() {
1326 CompilerOptions options = createCompilerOptions();
1327 String code =
1328 "function f() { return true + true + true + true + true + true; }";
1329 String expected = "var JSCompiler_alias_TRUE = true;" +
1330 "function f() { return JSCompiler_alias_TRUE + " +
1331 " JSCompiler_alias_TRUE + JSCompiler_alias_TRUE + " +
1332 " JSCompiler_alias_TRUE + JSCompiler_alias_TRUE + " +
1333 " JSCompiler_alias_TRUE; }";
1334 testSame(options, code);
1335
1336 options.aliasKeywords = true;
1337 test(options, code, expected);
1338 }
1339
1340 public void testRenameVars1() {
1341 CompilerOptions options = createCompilerOptions();
1342 String code =
1343 "var abc = 3; function f() { var xyz = 5; return abc + xyz; }";
1344 String local = "var abc = 3; function f() { var a = 5; return abc + a; }";
1345 String all = "var a = 3; function c() { var b = 5; return a + b; }";
1346 testSame(options, code);
1347
1348 options.variableRenaming = VariableRenamingPolicy.LOCAL;
1349 test(options, code, local);
1350
1351 options.variableRenaming = VariableRenamingPolicy.ALL;
1352 test(options, code, all);
1353
1354 options.reserveRawExports = true;
1355 }
1356
1357 public void testRenameVars2() {
1358 CompilerOptions options = createCompilerOptions();
1359 options.variableRenaming = VariableRenamingPolicy.ALL;
1360
1361 String code = "var abc = 3; function f() { window['a'] = 5; }";
1362 String noexport = "var a = 3; function b() { window['a'] = 5; }";
1363 String export = "var b = 3; function c() { window['a'] = 5; }";
1364
1365 options.reserveRawExports = false;
1366 test(options, code, noexport);
1367
1368 options.reserveRawExports = true;
1369 test(options, code, export);
1370 }
1371
1372 public void testShadowVaribles() {
1373 CompilerOptions options = createCompilerOptions();
1374 options.variableRenaming = VariableRenamingPolicy.LOCAL;
1375 options.shadowVariables = true;
1376 String code = "var f = function(x) { return function(y) {}}";
1377 String expected = "var f = function(a) { return function(a) {}}";
1378 test(options, code, expected);
1379 }
1380
1381 public void testRenameLabels() {
1382 CompilerOptions options = createCompilerOptions();
1383 String code = "longLabel: for(;true;) { break longLabel; }";
1384 String expected = "a: for(;true;) { break a; }";
1385 testSame(options, code);
1386
1387 options.labelRenaming = true;
1388 test(options, code, expected);
1389 }
1390
1391 public void testBadBreakStatementInIdeMode() {
1392 // Ensure that type-checking doesn't crash, even if the CFG is malformed.
1393 // This can happen in IDE mode.
1394 CompilerOptions options = createCompilerOptions();
1395 options.ideMode = true;
1396 options.checkTypes = true;
1397 test(options,
1398 "function f() { try { } catch(e) { break; } }",
1399 RhinoErrorReporter.PARSE_ERROR);
1400 }
1401
1402 public void testIssue63SourceMap() {
1403 CompilerOptions options = createCompilerOptions();
1404 String code = "var a;";
1405
1406 options.skipAllPasses = true;
1407 options.sourceMapOutputPath = "./src.map";
1408
1409 Compiler compiler = compile(options, code);
1410 compiler.toSource();
1411 }
1412
1413 public void testRegExp1() {
1414 CompilerOptions options = createCompilerOptions();
1415 options.foldConstants = true;
1416
1417 String code = "/(a)/.test(\"a\");";
1418
1419 testSame(options, code);
1420
1421 options.computeFunctionSideEffects = true;
1422
1423 String expected = "";
1424
1425 test(options, code, expected);
1426 }
1427
1428 public void testRegExp2() {
1429 CompilerOptions options = createCompilerOptions();
1430
1431 options.foldConstants = true;
1432
1433 String code = "/(a)/.test(\"a\");var a = RegExp.$1";
1434
1435 testSame(options, code);
1436
1437 options.computeFunctionSideEffects = true;
1438
1439 test(options, code, CheckRegExp.REGEXP_REFERENCE);
1440
1441 options.setWarningLevel(DiagnosticGroups.CHECK_REGEXP, CheckLevel.OFF);
1442
1443 testSame(options, code);
1444 }
1445
1446 public void testFoldLocals1() {
1447 CompilerOptions options = createCompilerOptions();
1448
1449 options.foldConstants = true;
1450
1451 // An external object, whose constructor has no side-effects,
1452 // and whose method "go" only modifies the object.
1453 String code = "new Widget().go();";
1454
1455 testSame(options, code);
1456
1457 options.computeFunctionSideEffects = true;
1458
1459 test(options, code, "");
1460 }
1461
1462 public void testFoldLocals2() {
1463 CompilerOptions options = createCompilerOptions();
1464
1465 options.foldConstants = true;
1466 options.checkTypes = true;
1467
1468 // An external function that returns a local object that the
1469 // method "go" that only modifies the object.
1470 String code = "widgetToken().go();";
1471
1472 testSame(options, code);
1473
1474 options.computeFunctionSideEffects = true;
1475
1476 test(options, code, "widgetToken()");
1477 }
1478
1479
1480 public void testFoldLocals3() {
1481 CompilerOptions options = createCompilerOptions();
1482
1483 options.foldConstants = true;
1484
1485 // A function "f" who returns a known local object, and a method that
1486 // modifies only modifies that.
1487 String definition = "function f(){return new Widget()}";
1488 String call = "f().go();";
1489 String code = definition + call;
1490
1491 testSame(options, code);
1492
1493 options.computeFunctionSideEffects = true;
1494
1495 // BROKEN
1496 //test(options, code, definition);
1497 testSame(options, code);
1498 }
1499
1500 public void testFoldLocals4() {
1501 CompilerOptions options = createCompilerOptions();
1502
1503 options.foldConstants = true;
1504
1505 String code = "/** @constructor */\n"
1506 + "function InternalWidget(){this.x = 1;}"
1507 + "InternalWidget.prototype.internalGo = function (){this.x = 2};"
1508 + "new InternalWidget().internalGo();";
1509
1510 testSame(options, code);
1511
1512 options.computeFunctionSideEffects = true;
1513
1514 String optimized = ""
1515 + "function InternalWidget(){this.x = 1;}"
1516 + "InternalWidget.prototype.internalGo = function (){this.x = 2};";
1517
1518 test(options, code, optimized);
1519 }
1520
1521 public void testFoldLocals5() {
1522 CompilerOptions options = createCompilerOptions();
1523
1524 options.foldConstants = true;
1525
1526 String code = ""
1527 + "function fn(){var a={};a.x={};return a}"
1528 + "fn().x.y = 1;";
1529
1530 // "fn" returns a unescaped local object, we should be able to fold it,
1531 // but we don't currently.
1532 String result = ""
1533 + "function fn(){var a={x:{}};return a}"
1534 + "fn().x.y = 1;";
1535
1536 test(options, code, result);
1537
1538 options.computeFunctionSideEffects = true;
1539
1540 test(options, code, result);
1541 }
1542
1543 public void testFoldLocals6() {
1544 CompilerOptions options = createCompilerOptions();
1545
1546 options.foldConstants = true;
1547
1548 String code = ""
1549 + "function fn(){return {}}"
1550 + "fn().x.y = 1;";
1551
1552 testSame(options, code);
1553
1554 options.computeFunctionSideEffects = true;
1555
1556 testSame(options, code);
1557 }
1558
1559 public void testFoldLocals7() {
1560 CompilerOptions options = createCompilerOptions();
1561
1562 options.foldConstants = true;
1563
1564 String code = ""
1565 + "function InternalWidget(){return [];}"
1566 + "Array.prototype.internalGo = function (){this.x = 2};"
1567 + "InternalWidget().internalGo();";
1568
1569 testSame(options, code);
1570
1571 options.computeFunctionSideEffects = true;
1572
1573 String optimized = ""
1574 + "function InternalWidget(){return [];}"
1575 + "Array.prototype.internalGo = function (){this.x = 2};";
1576
1577 test(options, code, optimized);
1578 }
1579
1580 public void testVarDeclarationsIntoFor() {
1581 CompilerOptions options = createCompilerOptions();
1582
1583 options.collapseVariableDeclarations = false;
1584
1585 String code = "var a = 1; for (var b = 2; ;) {}";
1586
1587 testSame(options, code);
1588
1589 options.collapseVariableDeclarations = true;
1590
1591 test(options, code, "for (var a = 1, b = 2; ;) {}");
1592 }
1593
1594 public void testExploitAssigns() {
1595 CompilerOptions options = createCompilerOptions();
1596
1597 options.collapseVariableDeclarations = false;
1598
1599 String code = "a = 1; b = a; c = b";
1600
1601 testSame(options, code);
1602
1603 options.collapseVariableDeclarations = true;
1604
1605 test(options, code, "c=b=a=1");
1606 }
1607
1608 public void testRecoverOnBadExterns() throws Exception {
1609 // This test is for a bug in a very narrow set of circumstances:
1610 // 1) externs validation has to be off.
1611 // 2) aliasExternals has to be on.
1612 // 3) The user has to reference a "normal" variable in externs.
1613 // This case is handled at checking time by injecting a
1614 // synthetic extern variable, and adding a "@suppress {duplicate}" to
1615 // the normal code at compile time. But optimizations may remove that
1616 // annotation, so we need to make sure that the variable declarations
1617 // are de-duped before that happens.
1618 CompilerOptions options = createCompilerOptions();
1619
1620 options.aliasExternals = true;
1621 externs = ImmutableList.of(
1622 SourceFile.fromCode("externs", "extern.foo"));
1623
1624 test(options,
1625 "var extern; " +
1626 "function f() { return extern + extern + extern + extern; }",
1627 "var extern; " +
1628 "function f() { return extern + extern + extern + extern; }",
1629 VarCheck.UNDEFINED_EXTERN_VAR_ERROR);
1630 }
1631
1632 public void testDuplicateVariablesInExterns() {
1633 CompilerOptions options = createCompilerOptions();
1634 options.checkSymbols = true;
1635 externs = ImmutableList.of(
1636 SourceFile.fromCode("externs",
1637 "var externs = {}; /** @suppress {duplicate} */ var externs = {};"));
1638 testSame(options, "");
1639 }
1640
1641 public void testLanguageMode() {
1642 CompilerOptions options = createCompilerOptions();
1643 options.setLanguageIn(LanguageMode.ECMASCRIPT3);
1644
1645 String code = "var a = {get f(){}}";
1646
1647 Compiler compiler = compile(options, code);
1648 checkUnexpectedErrorsOrWarnings(compiler, 1);
1649 assertEquals(
1650 "JSC_PARSE_ERROR. Parse error. " +
1651 "getters are not supported in older versions of JS. " +
1652 "If you are targeting newer versions of JS, " +
1653 "set the appropriate language_in option. " +
1654 "at i0 line 1 : 0",
1655 compiler.getErrors()[0].toString());
1656
1657 options.setLanguageIn(LanguageMode.ECMASCRIPT5);
1658
1659 testSame(options, code);
1660
1661 options.setLanguageIn(LanguageMode.ECMASCRIPT5_STRICT);
1662
1663 testSame(options, code);
1664 }
1665
1666 public void testLanguageMode2() {
1667 CompilerOptions options = createCompilerOptions();
1668 options.setLanguageIn(LanguageMode.ECMASCRIPT3);
1669 options.setWarningLevel(DiagnosticGroups.ES5_STRICT, CheckLevel.OFF);
1670
1671 String code = "var a = 2; delete a;";
1672
1673 testSame(options, code);
1674
1675 options.setLanguageIn(LanguageMode.ECMASCRIPT5);
1676
1677 testSame(options, code);
1678
1679 options.setLanguageIn(LanguageMode.ECMASCRIPT5_STRICT);
1680
1681 test(options,
1682 code,
1683 code,
1684 StrictModeCheck.DELETE_VARIABLE);
1685 }
1686
1687 public void testIssue598() {
1688 CompilerOptions options = createCompilerOptions();
1689 options.setLanguageIn(LanguageMode.ECMASCRIPT5_STRICT);
1690 WarningLevel.VERBOSE.setOptionsForWarningLevel(options);
1691
1692 options.setLanguageIn(LanguageMode.ECMASCRIPT5);
1693
1694 String code =
1695 "'use strict';\n" +
1696 "function App() {}\n" +
1697 "App.prototype = {\n" +
1698 " get appData() { return this.appData_; },\n" +
1699 " set appData(data) { this.appData_ = data; }\n" +
1700 "};";
1701
1702 testSame(options, code);
1703 }
1704
1705 public void testIssue701() {
1706 // Check ASCII art in license comments.
1707 String ascii = "/**\n" +
1708 " * @preserve\n" +
1709 " This\n" +
1710 " is\n" +
1711 " ASCII ART\n" +
1712 "*/";
1713 String result = "/*\n\n" +
1714 " This\n" +
1715 " is\n" +
1716 " ASCII ART\n" +
1717 "*/\n";
1718 testSame(createCompilerOptions(), ascii);
1719 assertEquals(result, lastCompiler.toSource());
1720 }
1721
1722 public void testIssue724() {
1723 CompilerOptions options = createCompilerOptions();
1724 CompilationLevel.ADVANCED_OPTIMIZATIONS
1725 .setOptionsForCompilationLevel(options);
1726 String code =
1727 "isFunction = function(functionToCheck) {" +
1728 " var getType = {};" +
1729 " return functionToCheck && " +
1730 " getType.toString.apply(functionToCheck) === " +
1731 " '[object Function]';" +
1732 "};";
1733 String result =
1734 "isFunction=function(a){var b={};" +
1735 "return a&&\"[object Function]\"===b.b.a(a)}";
1736
1737 test(options, code, result);
1738 }
1739
1740 public void testIssue730() {
1741 CompilerOptions options = createCompilerOptions();
1742 CompilationLevel.ADVANCED_OPTIMIZATIONS
1743 .setOptionsForCompilationLevel(options);
1744
1745 String code =
1746 "/** @constructor */function A() {this.foo = 0; Object.seal(this);}\n" +
1747 "/** @constructor */function B() {this.a = new A();}\n" +
1748 "B.prototype.dostuff = function() {this.a.foo++;alert('hi');}\n" +
1749 "new B().dostuff();\n";
1750
1751 test(options,
1752 code,
1753 "function a(){this.b=0;Object.seal(this)}" +
1754 "(new function(){this.a=new a}).a.b++;" +
1755 "alert(\"hi\")");
1756
1757 options.removeUnusedClassProperties = true;
1758
1759 // This is still a problem when removeUnusedClassProperties are enabled.
1760 test(options,
1761 code,
1762 "function a(){Object.seal(this)}" +
1763 "(new function(){this.a=new a}).a.b++;" +
1764 "alert(\"hi\")");
1765 }
1766
1767 public void testCoaleseVariables() {
1768 CompilerOptions options = createCompilerOptions();
1769
1770 options.foldConstants = false;
1771 options.coalesceVariableNames = true;
1772
1773 String code =
1774 "function f(a) {" +
1775 " if (a) {" +
1776 " return a;" +
1777 " } else {" +
1778 " var b = a;" +
1779 " return b;" +
1780 " }" +
1781 " return a;" +
1782 "}";
1783 String expected =
1784 "function f(a) {" +
1785 " if (a) {" +
1786 " return a;" +
1787 " } else {" +
1788 " a = a;" +
1789 " return a;" +
1790 " }" +
1791 " return a;" +
1792 "}";
1793
1794 test(options, code, expected);
1795
1796 options.foldConstants = true;
1797 options.coalesceVariableNames = false;
1798
1799 code =
1800 "function f(a) {" +
1801 " if (a) {" +
1802 " return a;" +
1803 " } else {" +
1804 " var b = a;" +
1805 " return b;" +
1806 " }" +
1807 " return a;" +
1808 "}";
1809 expected =
1810 "function f(a) {" +
1811 " if (!a) {" +
1812 " var b = a;" +
1813 " return b;" +
1814 " }" +
1815 " return a;" +
1816 "}";
1817
1818 test(options, code, expected);
1819
1820 options.foldConstants = true;
1821 options.coalesceVariableNames = true;
1822
1823 expected =
1824 "function f(a) {" +
1825 " return a;" +
1826 "}";
1827
1828 test(options, code, expected);
1829 }
1830
1831 public void testLateStatementFusion() {
1832 CompilerOptions options = createCompilerOptions();
1833 options.foldConstants = true;
1834 test(options,
1835 "while(a){a();if(b){b();b()}}",
1836 "for(;a;)a(),b&&(b(),b())");
1837 }
1838
1839 public void testLateConstantReordering() {
1840 CompilerOptions options = createCompilerOptions();
1841 options.foldConstants = true;
1842 test(options,
1843 "if (x < 1 || x > 1 || 1 < x || 1 > x) { alert(x) }",
1844 " (1 > x || 1 < x || 1 < x || 1 > x) && alert(x) ");
1845 }
1846
1847 public void testsyntheticBlockOnDeadAssignments() {
1848 CompilerOptions options = createCompilerOptions();
1849 options.deadAssignmentElimination = true;
1850 options.removeUnusedVars = true;
1851 options.syntheticBlockStartMarker = "START";
1852 options.syntheticBlockEndMarker = "END";
1853 test(options, "var x; x = 1; START(); x = 1;END();x()",
1854 "var x; x = 1;{START();{x = 1}END()}x()");
1855 }
1856
1857 public void testBug4152835() {
1858 CompilerOptions options = createCompilerOptions();
1859 options.foldConstants = true;
1860 options.syntheticBlockStartMarker = "START";
1861 options.syntheticBlockEndMarker = "END";
1862 test(options, "START();END()", "{START();{}END()}");
1863 }
1864
1865 public void testBug5786871() {
1866 CompilerOptions options = createCompilerOptions();
1867 options.ideMode = true;
1868 test(options, "function () {}", RhinoErrorReporter.PARSE_ERROR);
1869 }
1870
1871 public void testIssue378() {
1872 CompilerOptions options = createCompilerOptions();
1873 options.inlineVariables = true;
1874 options.flowSensitiveInlineVariables = true;
1875 testSame(options, "function f(c) {var f = c; arguments[0] = this;" +
1876 " f.apply(this, arguments); return this;}");
1877 }
1878
1879 public void testIssue550() {
1880 CompilerOptions options = createCompilerOptions();
1881 CompilationLevel.SIMPLE_OPTIMIZATIONS
1882 .setOptionsForCompilationLevel(options);
1883 options.foldConstants = true;
1884 options.inlineVariables = true;
1885 options.flowSensitiveInlineVariables = true;
1886 test(options,
1887 "function f(h) {\n" +
1888 " var a = h;\n" +
1889 " a = a + 'x';\n" +
1890 " a = a + 'y';\n" +
1891 " return a;\n" +
1892 "}",
1893 // This should eventually get inlined completely.
1894 "function f(a) { a += 'x'; return a += 'y'; }");
1895 }
1896
1897 public void testIssue284() {
1898 CompilerOptions options = createCompilerOptions();
1899 options.smartNameRemoval = true;
1900 test(options,
1901 "var goog = {};" +
1902 "goog.inherits = function(x, y) {};" +
1903 "var ns = {};" +
1904 "/** @constructor */" +
1905 "ns.PageSelectionModel = function() {};" +
1906 "/** @constructor */" +
1907 "ns.PageSelectionModel.FooEvent = function() {};" +
1908 "/** @constructor */" +
1909 "ns.PageSelectionModel.SelectEvent = function() {};" +
1910 "goog.inherits(ns.PageSelectionModel.ChangeEvent," +
1911 " ns.PageSelectionModel.FooEvent);",
1912 "");
1913 }
1914
1915 public void testIssue772() throws Exception {
1916 CompilerOptions options = createCompilerOptions();
1917 options.closurePass = true;
1918 options.checkTypes = true;
1919 test(
1920 options,
1921 "/** @const */ var a = {};" +
1922 "/** @const */ a.b = {};" +
1923 "/** @const */ a.b.c = {};" +
1924 "goog.scope(function() {" +
1925 " var b = a.b;" +
1926 " var c = b.c;" +
1927 " /** @typedef {string} */" +
1928 " c.MyType;" +
1929 " /** @param {c.MyType} x The variable. */" +
1930 " c.myFunc = function(x) {};" +
1931 "});",
1932 "/** @const */ var a = {};" +
1933 "/** @const */ a.b = {};" +
1934 "/** @const */ a.b.c = {};" +
1935 "a.b.c.MyType;" +
1936 "a.b.c.myFunc = function(x) {};");
1937 }
1938
1939 public void testCodingConvention() {
1940 Compiler compiler = new Compiler();
1941 compiler.initOptions(new CompilerOptions());
1942 assertEquals(
1943 compiler.getCodingConvention().getClass().toString(),
1944 ClosureCodingConvention.class.toString());
1945 }
1946
1947 public void testJQueryStringSplitLoops() {
1948 CompilerOptions options = createCompilerOptions();
1949 options.foldConstants = true;
1950 test(options,
1951 "var x=['1','2','3','4','5','6','7']",
1952 "var x='1234567'.split('')");
1953
1954 options = createCompilerOptions();
1955 options.foldConstants = true;
1956 options.computeFunctionSideEffects = false;
1957 options.removeUnusedVars = true;
1958
1959 // If we do splits too early, it would add a side-effect to x.
1960 test(options,
1961 "var x=['1','2','3','4','5','6','7']",
1962 "");
1963
1964 }
1965
1966 public void testAlwaysRunSafetyCheck() {
1967 CompilerOptions options = createCompilerOptions();
1968 options.checkSymbols = false;
1969 options.customPasses = ArrayListMultimap.create();
1970 options.customPasses.put(
1971 CustomPassExecutionTime.BEFORE_OPTIMIZATIONS,
1972 new CompilerPass() {
1973 @Override public void process(Node externs, Node root) {
1974 Node var = root.getLastChild().getFirstChild();
1975 assertEquals(Token.VAR, var.getType());
1976 var.detachFromParent();
1977 }
1978 });
1979 try {
1980 test(options,
1981 "var x = 3; function f() { return x + z; }",
1982 "function f() { return x + z; }");
1983 fail("Expected run-time exception");
1984 } catch (RuntimeException e) {
1985 assertTrue(e.getMessage().indexOf("Unexpected variable x") != -1);
1986 }
1987 }
1988
1989 public void testSuppressEs5StrictWarning() {
1990 CompilerOptions options = createCompilerOptions();
1991 options.setWarningLevel(DiagnosticGroups.ES5_STRICT, CheckLevel.WARNING);
1992 test(options,
1993 "/** @suppress{es5Strict} */\n" +
1994 "function f() { var arguments; }",
1995 "function f() {}");
1996 }
1997
1998 public void testCheckProvidesWarning() {
1999 CompilerOptions options = createCompilerOptions();
2000 options.setWarningLevel(DiagnosticGroups.CHECK_PROVIDES, CheckLevel.WARNING);
2001 options.setCheckProvides(CheckLevel.WARNING);
2002 test(options,
2003 "/** @constructor */\n" +
2004 "function f() { var arguments; }",
2005 DiagnosticType.warning("JSC_MISSING_PROVIDE", "missing goog.provide(''{0}'')"));
2006 }
2007
2008 public void testSuppressCheckProvidesWarning() {
2009 CompilerOptions options = createCompilerOptions();
2010 options.setWarningLevel(DiagnosticGroups.CHECK_PROVIDES, CheckLevel.WARNING);
2011 options.setCheckProvides(CheckLevel.WARNING);
2012 testSame(options,
2013 "/** @constructor\n" +
2014 " * @suppress{checkProvides} */\n" +
2015 "function f() {}");
2016 }
2017
2018 public void testSuppressCastWarning() {
2019 CompilerOptions options = createCompilerOptions();
2020 options.setWarningLevel(DiagnosticGroups.CHECK_TYPES, CheckLevel.WARNING);
2021
2022 normalizeResults = true;
2023
2024 test(options,
2025 "function f() { var xyz = /** @type {string} */ (0); }",
2026 DiagnosticType.warning(
2027 "JSC_INVALID_CAST", "invalid cast"));
2028
2029 testSame(options,
2030 "/** @suppress {invalidCasts} */\n" +
2031 "function f() { var xyz = /** @type {string} */ (0); }");
2032
2033 testSame(options,
2034 "/** @const */ var g = {};" +
2035 "/** @suppress {invalidCasts} */" +
2036 "g.a = g.b = function() { var xyz = /** @type {string} */ (0); }");
2037 }
2038
2039 public void testLhsCast() {
2040 CompilerOptions options = createCompilerOptions();
2041 test(
2042 options,
2043 "/** @const */ var g = {};" +
2044 "/** @type {number} */ (g.foo) = 3;",
2045 "/** @const */ var g = {};" +
2046 "g.foo = 3;");
2047 }
2048
2049 public void testRenamePrefix() {
2050 String code = "var x = {}; function f(y) {}";
2051 CompilerOptions options = createCompilerOptions();
2052 options.renamePrefix = "G_";
2053 options.variableRenaming = VariableRenamingPolicy.ALL;
2054 test(options, code, "var G_={}; function G_a(a) {}");
2055 }
2056
2057 public void testRenamePrefixNamespace() {
2058 String code =
2059 "var x = {}; x.FOO = 5; x.bar = 3;";
2060
2061 CompilerOptions options = createCompilerOptions();
2062 testSame(options, code);
2063
2064 options.collapseProperties = true;
2065 options.renamePrefixNamespace = "_";
2066 test(options, code, "_.x$FOO = 5; _.x$bar = 3;");
2067 }
2068
2069 public void testRenamePrefixNamespaceProtectSideEffects() {
2070 String code = "var x = null; try { +x.FOO; } catch (e) {}";
2071
2072 CompilerOptions options = createCompilerOptions();
2073 testSame(options, code);
2074
2075 CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(
2076 options);
2077 options.renamePrefixNamespace = "_";
2078 test(options, code, "_.x = null; try { +_.x.FOO; } catch (e) {}");
2079 }
2080
2081 public void testRenamePrefixNamespaceActivatesMoveFunctionDeclarations() {
2082 CompilerOptions options = createCompilerOptions();
2083 String code = "var x = f; function f() { return 3; }";
2084 testSame(options, code);
2085 assertFalse(options.moveFunctionDeclarations);
2086 options.renamePrefixNamespace = "_";
2087 test(options, code, "_.f = function() { return 3; }; _.x = _.f;");
2088 }
2089
2090 public void testBrokenNameSpace() {
2091 CompilerOptions options = createCompilerOptions();
2092 String code = "var goog; goog.provide('i.am.on.a.Horse');" +
2093 "i.am.on.a.Horse = function() {};" +
2094 "i.am.on.a.Horse.prototype.x = function() {};" +
2095 "i.am.on.a.Boat.prototype.y = function() {}";
2096 options.closurePass = true;
2097 options.collapseProperties = true;
2098 options.smartNameRemoval = true;
2099 test(options, code, "");
2100 }
2101
2102 public void testNamelessParameter() {
2103 CompilerOptions options = createCompilerOptions();
2104 CompilationLevel.ADVANCED_OPTIMIZATIONS
2105 .setOptionsForCompilationLevel(options);
2106 String code =
2107 "var impl_0;" +
2108 "$load($init());" +
2109 "function $load(){" +
2110 " window['f'] = impl_0;" +
2111 "}" +
2112 "function $init() {" +
2113 " impl_0 = {};" +
2114 "}";
2115 String result =
2116 "window.f = {};";
2117 test(options, code, result);
2118 }
2119
2120 public void testHiddenSideEffect() {
2121 CompilerOptions options = createCompilerOptions();
2122 CompilationLevel.ADVANCED_OPTIMIZATIONS
2123 .setOptionsForCompilationLevel(options);
2124 options.setAliasExternals(true);
2125 String code =
2126 "window.offsetWidth;";
2127 String result =
2128 "window.offsetWidth;";
2129 test(options, code, result);
2130 }
2131
2132 public void testNegativeZero() {
2133 CompilerOptions options = createCompilerOptions();
2134 CompilationLevel.ADVANCED_OPTIMIZATIONS
2135 .setOptionsForCompilationLevel(options);
2136 test(options,
2137 "function bar(x) { return x; }\n" +
2138 "function foo(x) { print(x / bar(0));\n" +
2139 " print(x / bar(-0)); }\n" +
2140 "foo(3);",
2141 "print(3/0);print(3/-0);");
2142 }
2143
2144 public void testSingletonGetter1() {
2145 CompilerOptions options = createCompilerOptions();
2146 CompilationLevel.ADVANCED_OPTIMIZATIONS
2147 .setOptionsForCompilationLevel(options);
2148 options.setCodingConvention(new ClosureCodingConvention());
2149 test(options,
2150 "/** @const */\n" +
2151 "var goog = goog || {};\n" +
2152 "goog.addSingletonGetter = function(ctor) {\n" +
2153 " ctor.getInstance = function() {\n" +
2154 " return ctor.instance_ || (ctor.instance_ = new ctor());\n" +
2155 " };\n" +
2156 "};" +
2157 "function Foo() {}\n" +
2158 "goog.addSingletonGetter(Foo);" +
2159 "Foo.prototype.bar = 1;" +
2160 "function Bar() {}\n" +
2161 "goog.addSingletonGetter(Bar);" +
2162 "Bar.prototype.bar = 1;",
2163 "");
2164 }
2165
2166 public void testIncompleteFunction1() {
2167 CompilerOptions options = createCompilerOptions();
2168 options.ideMode = true;
2169 DiagnosticType[] warnings = new DiagnosticType[]{
2170 RhinoErrorReporter.PARSE_ERROR,
2171 RhinoErrorReporter.PARSE_ERROR};
2172 test(options,
2173 new String[] { "var foo = {bar: function(e) }" },
2174 new String[] { "var foo = {bar: function(e){}};" },
2175 warnings
2176 );
2177 }
2178
2179 public void testIncompleteFunction2() {
2180 CompilerOptions options = createCompilerOptions();
2181 options.ideMode = true;
2182 DiagnosticType[] warnings = new DiagnosticType[]{
2183 RhinoErrorReporter.PARSE_ERROR,
2184 RhinoErrorReporter.PARSE_ERROR,
2185 RhinoErrorReporter.PARSE_ERROR,
2186 RhinoErrorReporter.PARSE_ERROR,
2187 RhinoErrorReporter.PARSE_ERROR,
2188 RhinoErrorReporter.PARSE_ERROR};
2189 test(options,
2190 new String[] { "function hi" },
2191 new String[] { "function hi() {}" },
2192 warnings
2193 );
2194 }
2195
2196 public void testSortingOff() {
2197 CompilerOptions options = new CompilerOptions();
2198 options.closurePass = true;
2199 options.setCodingConvention(new ClosureCodingConvention());
2200 test(options,
2201 new String[] {
2202 "goog.require('goog.beer');",
2203 "goog.provide('goog.beer');"
2204 },
2205 ProcessClosurePrimitives.LATE_PROVIDE_ERROR);
2206 }
2207
2208 public void testUnboundedArrayLiteralInfiniteLoop() {
2209 CompilerOptions options = createCompilerOptions();
2210 options.ideMode = true;
2211 test(options,
2212 "var x = [1, 2",
2213 "var x = [1, 2]",
2214 RhinoErrorReporter.PARSE_ERROR);
2215 }
2216
2217 public void testProvideRequireSameFile() throws Exception {
2218 CompilerOptions options = createCompilerOptions();
2219 options.setDependencyOptions(
2220 new DependencyOptions()
2221 .setDependencySorting(true));
2222 options.closurePass = true;
2223 test(
2224 options,
2225 "goog.provide('x');\ngoog.require('x');",
2226 "var x = {};");
2227 }
2228
2229 public void testDependencySorting() throws Exception {
2230 CompilerOptions options = createCompilerOptions();
2231 options.setDependencyOptions(
2232 new DependencyOptions()
2233 .setDependencySorting(true));
2234 test(
2235 options,
2236 new String[] {
2237 "goog.require('x');",
2238 "goog.provide('x');",
2239 },
2240 new String[] {
2241 "goog.provide('x');",
2242 "goog.require('x');",
2243
2244 // For complicated reasons involving modules,
2245 // the compiler creates a synthetic source file.
2246 "",
2247 });
2248 }
2249
2250 public void testStrictWarningsGuard() throws Exception {
2251 CompilerOptions options = createCompilerOptions();
2252 options.checkTypes = true;
2253 options.addWarningsGuard(new StrictWarningsGuard());
2254
2255 Compiler compiler = compile(options,
2256 "/** @return {number} */ function f() { return true; }");
2257 assertEquals(1, compiler.getErrors().length);
2258 assertEquals(0, compiler.getWarnings().length);
2259 }
2260
2261 public void testStrictWarningsGuardEmergencyMode() throws Exception {
2262 CompilerOptions options = createCompilerOptions();
2263 options.checkTypes = true;
2264 options.addWarningsGuard(new StrictWarningsGuard());
2265 options.useEmergencyFailSafe();
2266
2267 Compiler compiler = compile(options,
2268 "/** @return {number} */ function f() { return true; }");
2269 assertEquals(0, compiler.getErrors().length);
2270 assertEquals(1, compiler.getWarnings().length);
2271 }
2272
2273 public void testInlineProperties() {
2274 CompilerOptions options = createCompilerOptions();
2275 CompilationLevel level = CompilationLevel.ADVANCED_OPTIMIZATIONS;
2276 level.setOptionsForCompilationLevel(options);
2277 level.setTypeBasedOptimizationOptions(options);
2278
2279 String code = "" +
2280 "var ns = {};\n" +
2281 "/** @constructor */\n" +
2282 "ns.C = function () {this.someProperty = 1}\n" +
2283 "alert(new ns.C().someProperty + new ns.C().someProperty);\n";
2284 assertTrue(options.inlineProperties);
2285 assertTrue(options.collapseProperties);
2286 // CollapseProperties used to prevent inlining this property.
2287 test(options, code, "alert(2);");
2288 }
2289
2290 public void testGoogDefineClass1() {
2291 CompilerOptions options = createCompilerOptions();
2292 CompilationLevel level = CompilationLevel.ADVANCED_OPTIMIZATIONS;
2293 level.setOptionsForCompilationLevel(options);
2294 level.setTypeBasedOptimizationOptions(options);
2295
2296 String code = "" +
2297 "var ns = {};\n" +
2298 "ns.C = goog.defineClass(null, {\n" +
2299 " /** @constructor */\n" +
2300 " constructor: function () {this.someProperty = 1}\n" +
2301 "});\n" +
2302 "alert(new ns.C().someProperty + new ns.C().someProperty);\n";
2303 assertTrue(options.inlineProperties);
2304 assertTrue(options.collapseProperties);
2305 // CollapseProperties used to prevent inlining this property.
2306 test(options, code, "alert(2);");
2307 }
2308
2309 public void testGoogDefineClass2() {
2310 CompilerOptions options = createCompilerOptions();
2311 CompilationLevel level = CompilationLevel.ADVANCED_OPTIMIZATIONS;
2312 level.setOptionsForCompilationLevel(options);
2313 level.setTypeBasedOptimizationOptions(options);
2314
2315 String code = "" +
2316 "var C = goog.defineClass(null, {\n" +
2317 " /** @constructor */\n" +
2318 " constructor: function () {this.someProperty = 1}\n" +
2319 "});\n" +
2320 "alert(new C().someProperty + new C().someProperty);\n";
2321 assertTrue(options.inlineProperties);
2322 assertTrue(options.collapseProperties);
2323 // CollapseProperties used to prevent inlining this property.
2324 test(options, code, "alert(2);");
2325 }
2326
2327 public void testGoogDefineClass3() {
2328 CompilerOptions options = createCompilerOptions();
2329 CompilationLevel level = CompilationLevel.ADVANCED_OPTIMIZATIONS;
2330 level.setOptionsForCompilationLevel(options);
2331 level.setTypeBasedOptimizationOptions(options);
2332 WarningLevel warnings = WarningLevel.VERBOSE;
2333 warnings.setOptionsForWarningLevel(options);
2334
2335 String code = "" +
2336 "var C = goog.defineClass(null, {\n" +
2337 " /** @constructor */\n" +
2338 " constructor: function () {\n" +
2339 " /** @type {number} */\n" +
2340 " this.someProperty = 1},\n" +
2341 " /** @param {string} a */\n" +
2342 " someMethod: function (a) {}\n" +
2343 "});" +
2344 "var x = new C();\n" +
2345 "x.someMethod(x.someProperty);\n";
2346 assertTrue(options.inlineProperties);
2347 assertTrue(options.collapseProperties);
2348 // CollapseProperties used to prevent inlining this property.
2349 test(options, code, TypeValidator.TYPE_MISMATCH_WARNING);
2350 }
2351
2352 public void testCheckConstants1() {
2353 CompilerOptions options = createCompilerOptions();
2354 CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS;
2355 level.setOptionsForCompilationLevel(options);
2356 WarningLevel warnings = WarningLevel.QUIET;
2357 warnings.setOptionsForWarningLevel(options);
2358
2359 String code = "" +
2360 "var foo; foo();\n" +
2361 "/** @const */\n" +
2362 "var x = 1; foo(); x = 2;\n";
2363 test(options, code, code);
2364 }
2365
2366 public void testCheckConstants2() {
2367 CompilerOptions options = createCompilerOptions();
2368 CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS;
2369 level.setOptionsForCompilationLevel(options);
2370 WarningLevel warnings = WarningLevel.DEFAULT;
2371 warnings.setOptionsForWarningLevel(options);
2372
2373 String code = "" +
2374 "var foo;\n" +
2375 "/** @const */\n" +
2376 "var x = 1; foo(); x = 2;\n";
2377 test(options, code, ConstCheck.CONST_REASSIGNED_VALUE_ERROR);
2378 }
2379
2380 public void testIssue787() {
2381 CompilerOptions options = createCompilerOptions();
2382 CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS;
2383 level.setOptionsForCompilationLevel(options);
2384 WarningLevel warnings = WarningLevel.DEFAULT;
2385 warnings.setOptionsForWarningLevel(options);
2386
2387 String code = "" +
2388 "function some_function() {\n" +
2389 " var fn1;\n" +
2390 " var fn2;\n" +
2391 "\n" +
2392 " if (any_expression) {\n" +
2393 " fn2 = external_ref;\n" +
2394 " fn1 = function (content) {\n" +
2395 " return fn2();\n" +
2396 " }\n" +
2397 " }\n" +
2398 "\n" +
2399 " return {\n" +
2400 " method1: function () {\n" +
2401 " if (fn1) fn1();\n" +
2402 " return true;\n" +
2403 " },\n" +
2404 " method2: function () {\n" +
2405 " return false;\n" +
2406 " }\n" +
2407 " }\n" +
2408 "}";
2409
2410 String result = "" +
2411 "function some_function() {\n" +
2412 " var a, b;\n" +
2413 " any_expression && (b = external_ref, a = function(a) {\n" +
2414 " return b()\n" +
2415 " });\n" +
2416 " return{method1:function() {\n" +
2417 " a && a();\n" +
2418 " return !0\n" +
2419 " }, method2:function() {\n" +
2420 " return !1\n" +
2421 " }}\n" +
2422 "}\n" +
2423 "";
2424
2425 test(options, code, result);
2426 }
2427
2428 public void testManyAdds() {
2429 CompilerOptions options = createCompilerOptions();
2430 CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS;
2431 level.setOptionsForCompilationLevel(options);
2432 WarningLevel warnings = WarningLevel.VERBOSE;
2433 warnings.setOptionsForWarningLevel(options);
2434
2435 int numAdds = 4750;
2436 StringBuilder original = new StringBuilder("var x = 0");
2437 for (int i = 0; i < numAdds; i++) {
2438 original.append(" + 1");
2439 }
2440 original.append(";");
2441 test(options, original.toString(), "var x = " + numAdds + ";");
2442 }
2443
2444 // Checks that the summary and the log in the output of PerformanceTracker
2445 // have the expected number of columns
2446 public void testPerfTracker() {
2447 ByteArrayOutputStream output = new ByteArrayOutputStream();
2448 PrintStream outstream = new PrintStream(output);
2449 Compiler compiler = new Compiler(outstream);
2450 CompilerOptions options = new CompilerOptions();
2451 List<SourceFile> inputs = Lists.newArrayList();
2452 List<SourceFile> externs = Lists.newArrayList();
2453
2454 options.setTracerMode(TracerMode.ALL);
2455 inputs.add(SourceFile.fromCode("foo", "function fun(){}"));
2456 compiler.compile(externs, inputs, options);
2457 outstream.flush();
2458 outstream.close();
2459 Pattern p = Pattern.compile(
2460 ".*Summary:\npass,runtime,runs,changingRuns,reduction,gzReduction" +
2461 ".*TOTAL:" +
2462 "\nRuntime\\(ms\\): [0-9]+" +
2463 "\n#Runs: [0-9]+" +
2464 "\n#Changing runs: [0-9]+" +
2465 "\n#Loopable runs: [0-9]+" +
2466 "\n#Changing loopable runs: [0-9]+" +
2467 "\nReduction\\(bytes\\): [0-9]+" +
2468 "\nGzReduction\\(bytes\\): [0-9]+" +
2469 "\nSize\\(bytes\\): [0-9]+" +
2470 "\nGzSize\\(bytes\\): [0-9]+" +
2471 "\n\nLog:\n" +
2472 "pass,runtime,runs,changingRuns,reduction,gzReduction,size,gzSize.*",
2473 Pattern.DOTALL);
2474 assertTrue(p.matcher(output.toString()).matches());
2475 }
2476
2477 /** Creates a CompilerOptions object with google coding conventions. */
2478 @Override
2479 protected CompilerOptions createCompilerOptions() {
2480 CompilerOptions options = new CompilerOptions();
2481 options.setCodingConvention(new GoogleCodingConvention());
2482 return options;
2483 }
2484 }