Debian Codegraph @

test/com/google/javascript/jscomp/CommandLineRunnerTest.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.base.Function;
20 import com.google.common.base.Joiner;
21 import com.google.common.base.Preconditions;
22 import com.google.common.base.Supplier;
23 import com.google.common.base.Suppliers;
24 import com.google.common.collect.ImmutableList;
25 import com.google.common.collect.Lists;
26 import com.google.common.collect.Maps;
27 import com.google.javascript.jscomp.AbstractCommandLineRunner.FlagUsageException;
28 import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
29 import com.google.javascript.rhino.Node;
30
31 import junit.framework.TestCase;
32
33 import java.io.ByteArrayOutputStream;
34 import java.io.IOException;
35 import java.io.PrintStream;
36 import java.util.List;
37 import java.util.Map;
38
39 /**
40 * Tests for {@link CommandLineRunner}.
41 *
42 * @author [email protected] (Nick Santos)
43 */
44 public class CommandLineRunnerTest extends TestCase {
45
46 private Compiler lastCompiler = null;
47 private CommandLineRunner lastCommandLineRunner = null;
48 private List<Integer> exitCodes = null;
49 private ByteArrayOutputStream outReader = null;
50 private ByteArrayOutputStream errReader = null;
51 private Map<Integer,String> filenames;
52
53 // If set, this will be appended to the end of the args list.
54 // For testing args parsing.
55 private String lastArg = null;
56
57 // If set to true, uses comparison by string instead of by AST.
58 private boolean useStringComparison = false;
59
60 private ModulePattern useModules = ModulePattern.NONE;
61
62 private enum ModulePattern {
63 NONE,
64 CHAIN,
65 STAR
66 }
67
68 private List<String> args = Lists.newArrayList();
69
70 /** Externs for the test */
71 private final List<SourceFile> DEFAULT_EXTERNS = ImmutableList.of(
72 SourceFile.fromCode("externs",
73 "var arguments;"
74 + "/**\n"
75 + " * @constructor\n"
76 + " * @param {...*} var_args\n"
77 + " * @nosideeffects\n"
78 + " * @throws {Error}\n"
79 + " */\n"
80 + "function Function(var_args) {}\n"
81 + "/**\n"
82 + " * @param {...*} var_args\n"
83 + " * @return {*}\n"
84 + " */\n"
85 + "Function.prototype.call = function(var_args) {};"
86 + "/**\n"
87 + " * @constructor\n"
88 + " * @param {...*} var_args\n"
89 + " * @return {!Array}\n"
90 + " */\n"
91 + "function Array(var_args) {}"
92 + "/**\n"
93 + " * @param {*=} opt_begin\n"
94 + " * @param {*=} opt_end\n"
95 + " * @return {!Array}\n"
96 + " * @this {Object}\n"
97 + " */\n"
98 + "Array.prototype.slice = function(opt_begin, opt_end) {};"
99 + "/** @constructor */ function Window() {}\n"
100 + "/** @type {string} */ Window.prototype.name;\n"
101 + "/** @type {Window} */ var window;"
102 + "/** @constructor */ function Element() {}"
103 + "Element.prototype.offsetWidth;"
104 + "/** @nosideeffects */ function noSideEffects() {}\n"
105 + "/** @param {...*} x */ function alert(x) {}\n")
106 );
107
108 private List<SourceFile> externs;
109
110 @Override
111 public void setUp() throws Exception {
112 super.setUp();
113 externs = DEFAULT_EXTERNS;
114 filenames = Maps.newHashMap();
115 lastCompiler = null;
116 lastArg = null;
117 outReader = new ByteArrayOutputStream();
118 errReader = new ByteArrayOutputStream();
119 useStringComparison = false;
120 useModules = ModulePattern.NONE;
121 args.clear();
122 exitCodes = Lists.newArrayList();
123 }
124
125 @Override
126 public void tearDown() throws Exception {
127 super.tearDown();
128 }
129
130 public void testUnknownAnnotation() {
131 args.add("--warning_level=VERBOSE");
132 test("/** @unknownTag */ function f() {}",
133 RhinoErrorReporter.BAD_JSDOC_ANNOTATION);
134
135 args.add("--extra_annotation_name=unknownTag");
136 testSame("/** @unknownTag */ function f() {}");
137 }
138
139 public void testWarningGuardOrdering1() {
140 args.add("--jscomp_error=globalThis");
141 args.add("--jscomp_off=globalThis");
142 testSame("function f() { this.a = 3; }");
143 }
144
145 public void testWarningGuardOrdering2() {
146 args.add("--jscomp_off=globalThis");
147 args.add("--jscomp_error=globalThis");
148 test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS);
149 }
150
151 public void testWarningGuardOrdering3() {
152 args.add("--jscomp_warning=globalThis");
153 args.add("--jscomp_off=globalThis");
154 testSame("function f() { this.a = 3; }");
155 }
156
157 public void testWarningGuardOrdering4() {
158 args.add("--jscomp_off=globalThis");
159 args.add("--jscomp_warning=globalThis");
160 test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS);
161 }
162
163 public void testSimpleModeLeavesUnusedParams() {
164 args.add("--compilation_level=SIMPLE_OPTIMIZATIONS");
165 testSame("window.f = function(a) {};");
166 }
167
168 public void testAdvancedModeRemovesUnusedParams() {
169 args.add("--compilation_level=ADVANCED_OPTIMIZATIONS");
170 test("window.f = function(a) {};", "window.a = function() {};");
171 }
172
173 public void testCheckGlobalThisOffByDefault() {
174 testSame("function f() { this.a = 3; }");
175 }
176
177 public void testCheckGlobalThisOnWithAdvancedMode() {
178 args.add("--compilation_level=ADVANCED_OPTIMIZATIONS");
179 test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS);
180 }
181
182 public void testCheckGlobalThisOnWithErrorFlag() {
183 args.add("--jscomp_error=globalThis");
184 test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS);
185 }
186
187 public void testCheckGlobalThisOff() {
188 args.add("--warning_level=VERBOSE");
189 args.add("--jscomp_off=globalThis");
190 testSame("function f() { this.a = 3; }");
191 }
192
193 public void testTypeCheckingOffByDefault() {
194 test("function f(x) { return x; } f();",
195 "function f(a) { return a; } f();");
196 }
197
198 public void testReflectedMethods() {
199 args.add("--compilation_level=ADVANCED_OPTIMIZATIONS");
200 test(
201 "/** @constructor */" +
202 "function Foo() {}" +
203 "Foo.prototype.handle = function(x, y) { alert(y); };" +
204 "var x = goog.reflect.object(Foo, {handle: 1});" +
205 "for (var i in x) { x[i].call(x); }" +
206 "window['Foo'] = Foo;",
207 "function a() {}" +
208 "a.prototype.a = function(e, d) { alert(d); };" +
209 "var b = goog.c.b(a, {a: 1}),c;" +
210 "for (c in b) { b[c].call(b); }" +
211 "window.Foo = a;");
212 }
213
214 public void testInlineVariables() {
215 args.add("--compilation_level=ADVANCED_OPTIMIZATIONS");
216 test(
217 "/** @constructor */ function F() { this.a = 0; }" +
218 "F.prototype.inc = function() { this.a++; return 10; };" +
219 "F.prototype.bar = function() { " +
220 " var c = 3; var val = inc(); this.a += val + c;" +
221 "};" +
222 "window['f'] = new F();" +
223 "window['f']['bar'] = window['f'].bar;",
224 "function a(){ this.a = 0; }" +
225 "a.prototype.b = function(){ var b=inc(); this.a += b + 3; };" +
226 "window.f = new a;" +
227 "window.f.bar = window.f.b");
228 }
229
230 public void testTypedAdvanced() {
231 args.add("--compilation_level=ADVANCED_OPTIMIZATIONS");
232 args.add("--use_types_for_optimization");
233 test(
234 "/** @constructor */\n" +
235 "function Foo() {}\n" +
236 "Foo.prototype.handle1 = function(x, y) { alert(y); };\n" +
237 "/** @constructor */\n" +
238 "function Bar() {}\n" +
239 "Bar.prototype.handle1 = function(x, y) {};\n" +
240 "new Foo().handle1(1, 2);\n" +
241 "new Bar().handle1(1, 2);\n",
242 "alert(2)");
243 }
244
245 public void testTypeCheckingOnWithVerbose() {
246 args.add("--warning_level=VERBOSE");
247 test("function f(x) { return x; } f();", TypeCheck.WRONG_ARGUMENT_COUNT);
248 }
249
250 public void testTypeParsingOffByDefault() {
251 testSame("/** @return {number */ function f(a) { return a; }");
252 }
253
254 public void testTypeParsingOnWithVerbose() {
255 args.add("--warning_level=VERBOSE");
256 test("/** @return {number */ function f(a) { return a; }",
257 RhinoErrorReporter.TYPE_PARSE_ERROR);
258 test("/** @return {n} */ function f(a) { return a; }",
259 RhinoErrorReporter.TYPE_PARSE_ERROR);
260 }
261
262 public void testTypeCheckOverride1() {
263 args.add("--warning_level=VERBOSE");
264 args.add("--jscomp_off=checkTypes");
265 testSame("var x = x || {}; x.f = function() {}; x.f(3);");
266 }
267
268 public void testTypeCheckOverride2() {
269 args.add("--warning_level=DEFAULT");
270 testSame("var x = x || {}; x.f = function() {}; x.f(3);");
271
272 args.add("--jscomp_warning=checkTypes");
273 test("var x = x || {}; x.f = function() {}; x.f(3);",
274 TypeCheck.WRONG_ARGUMENT_COUNT);
275 }
276
277 public void testCheckSymbolsOffForDefault() {
278 args.add("--warning_level=DEFAULT");
279 test("x = 3; var y; var y;", "x=3; var y;");
280 }
281
282 public void testCheckSymbolsOnForVerbose() {
283 args.add("--warning_level=VERBOSE");
284 test("x = 3;", VarCheck.UNDEFINED_VAR_ERROR);
285 test("var y; var y;", SyntacticScopeCreator.VAR_MULTIPLY_DECLARED_ERROR);
286 }
287
288 public void testCheckSymbolsOverrideForVerbose() {
289 args.add("--warning_level=VERBOSE");
290 args.add("--jscomp_off=undefinedVars");
291 testSame("x = 3;");
292 }
293
294 public void testCheckSymbolsOverrideForQuiet() {
295 args.add("--warning_level=QUIET");
296 args.add("--jscomp_error=undefinedVars");
297 test("x = 3;", VarCheck.UNDEFINED_VAR_ERROR);
298 }
299
300 public void testCheckUndefinedProperties1() {
301 args.add("--warning_level=VERBOSE");
302 args.add("--jscomp_error=missingProperties");
303 test("var x = {}; var y = x.bar;", TypeCheck.INEXISTENT_PROPERTY);
304 }
305
306 public void testCheckUndefinedProperties2() {
307 args.add("--warning_level=VERBOSE");
308 args.add("--jscomp_off=missingProperties");
309 test("var x = {}; var y = x.bar;", CheckGlobalNames.UNDEFINED_NAME_WARNING);
310 }
311
312 public void testCheckUndefinedProperties3() {
313 args.add("--warning_level=VERBOSE");
314 test("function f() {var x = {}; var y = x.bar;}",
315 TypeCheck.INEXISTENT_PROPERTY);
316 }
317
318 public void testDuplicateParams() {
319 test("function f(a, a) {}", RhinoErrorReporter.DUPLICATE_PARAM);
320 assertTrue(lastCompiler.hasHaltingErrors());
321 }
322
323 public void testDefineFlag() {
324 args.add("--define=FOO");
325 args.add("--define=\"BAR=5\"");
326 args.add("--D"); args.add("CCC");
327 args.add("-D"); args.add("DDD");
328 test("/** @define {boolean} */ var FOO = false;" +
329 "/** @define {number} */ var BAR = 3;" +
330 "/** @define {boolean} */ var CCC = false;" +
331 "/** @define {boolean} */ var DDD = false;",
332 "var FOO = !0, BAR = 5, CCC = !0, DDD = !0;");
333 }
334
335 public void testDefineFlag2() {
336 args.add("--define=FOO='x\"'");
337 test("/** @define {string} */ var FOO = \"a\";",
338 "var FOO = \"x\\\"\";");
339 }
340
341 public void testDefineFlag3() {
342 args.add("--define=FOO=\"x'\"");
343 test("/** @define {string} */ var FOO = \"a\";",
344 "var FOO = \"x'\";");
345 }
346
347 public void testScriptStrictModeNoWarning() {
348 test("'use strict';", "");
349 test("'no use strict';", CheckSideEffects.USELESS_CODE_ERROR);
350 }
351
352 public void testFunctionStrictModeNoWarning() {
353 test("function f() {'use strict';}", "function f() {}");
354 test("function f() {'no use strict';}",
355 CheckSideEffects.USELESS_CODE_ERROR);
356 }
357
358 public void testQuietMode() {
359 args.add("--warning_level=DEFAULT");
360 test("/** @const \n * @const */ var x;",
361 RhinoErrorReporter.PARSE_ERROR);
362 args.add("--warning_level=QUIET");
363 testSame("/** @const \n * @const */ var x;");
364 }
365
366 public void testProcessClosurePrimitives() {
367 test("var goog = {}; goog.provide('goog.dom');",
368 "var goog = {dom:{}};");
369 args.add("--process_closure_primitives=false");
370 testSame("var goog = {}; goog.provide('goog.dom');");
371 }
372
373 public void testGetMsgWiring() throws Exception {
374 test("var goog = {}; goog.getMsg = function(x) { return x; };" +
375 "/** @desc A real foo. */ var MSG_FOO = goog.getMsg('foo');",
376 "var goog={getMsg:function(a){return a}}, " +
377 "MSG_FOO=goog.getMsg('foo');");
378 args.add("--compilation_level=ADVANCED_OPTIMIZATIONS");
379 test("var goog = {}; goog.getMsg = function(x) { return x; };" +
380 "/** @desc A real foo. */ var MSG_FOO = goog.getMsg('foo');" +
381 "window['foo'] = MSG_FOO;",
382 "window.foo = 'foo';");
383 }
384
385 public void testCssNameWiring() throws Exception {
386 test("var goog = {}; goog.getCssName = function() {};" +
387 "goog.setCssNameMapping = function() {};" +
388 "goog.setCssNameMapping({'goog': 'a', 'button': 'b'});" +
389 "var a = goog.getCssName('goog-button');" +
390 "var b = goog.getCssName('css-button');" +
391 "var c = goog.getCssName('goog-menu');" +
392 "var d = goog.getCssName('css-menu');",
393 "var goog = { getCssName: function() {}," +
394 " setCssNameMapping: function() {} }," +
395 " a = 'a-b'," +
396 " b = 'css-b'," +
397 " c = 'a-menu'," +
398 " d = 'css-menu';");
399 }
400
401
402 //////////////////////////////////////////////////////////////////////////////
403 // Integration tests
404
405 public void testIssue70a() {
406 test("function foo({}) {}", RhinoErrorReporter.PARSE_ERROR);
407 }
408
409 public void testIssue70b() {
410 test("function foo([]) {}", RhinoErrorReporter.PARSE_ERROR);
411 }
412
413 public void testIssue81() {
414 args.add("--compilation_level=ADVANCED_OPTIMIZATIONS");
415 useStringComparison = true;
416 test("eval('1'); var x = eval; x('2');",
417 "eval(\"1\");(0,eval)(\"2\");");
418 }
419
420 public void testIssue115() {
421 args.add("--compilation_level=SIMPLE_OPTIMIZATIONS");
422 args.add("--jscomp_off=es5Strict");
423 args.add("--warning_level=VERBOSE");
424 test("function f() { " +
425 " var arguments = Array.prototype.slice.call(arguments, 0);" +
426 " return arguments[0]; " +
427 "}",
428 "function f() { " +
429 " arguments = Array.prototype.slice.call(arguments, 0);" +
430 " return arguments[0]; " +
431 "}");
432 }
433
434 public void testIssue297() {
435 args.add("--compilation_level=SIMPLE_OPTIMIZATIONS");
436 test("function f(p) {" +
437 " var x;" +
438 " return ((x=p.id) && (x=parseInt(x.substr(1))) && x>0);" +
439 "}",
440 "function f(b) {" +
441 " var a;" +
442 " return ((a=b.id) && (a=parseInt(a.substr(1))) && 0<a);" +
443 "}");
444 }
445
446 public void testHiddenSideEffect() {
447 args.add("--compilation_level=ADVANCED_OPTIMIZATIONS");
448 test("element.offsetWidth;",
449 "element.offsetWidth", CheckSideEffects.USELESS_CODE_ERROR);
450 }
451
452 public void testIssue504() {
453 args.add("--compilation_level=ADVANCED_OPTIMIZATIONS");
454 test("void function() { alert('hi'); }();",
455 "alert('hi');void 0", CheckSideEffects.USELESS_CODE_ERROR);
456 }
457
458 public void testIssue601() {
459 args.add("--compilation_level=WHITESPACE_ONLY");
460 test("function f() { return '\\v' == 'v'; } window['f'] = f;",
461 "function f(){return'\\v'=='v'}window['f']=f");
462 }
463
464 public void testIssue601b() {
465 args.add("--compilation_level=ADVANCED_OPTIMIZATIONS");
466 test("function f() { return '\\v' == 'v'; } window['f'] = f;",
467 "window.f=function(){return'\\v'=='v'}");
468 }
469
470 public void testIssue601c() {
471 args.add("--compilation_level=ADVANCED_OPTIMIZATIONS");
472 test("function f() { return '\\u000B' == 'v'; } window['f'] = f;",
473 "window.f=function(){return'\\u000B'=='v'}");
474 }
475
476 public void testIssue846() {
477 args.add("--compilation_level=ADVANCED_OPTIMIZATIONS");
478 testSame(
479 "try { new Function('this is an error'); } catch(a) { alert('x'); }");
480 }
481
482 public void testDebugFlag1() {
483 args.add("--compilation_level=SIMPLE_OPTIMIZATIONS");
484 args.add("--debug=false");
485 test("function foo(a) {}",
486 "function foo(a) {}");
487 }
488
489 public void testDebugFlag2() {
490 args.add("--compilation_level=SIMPLE_OPTIMIZATIONS");
491 args.add("--debug=true");
492 test("function foo(a) {alert(a)}",
493 "function foo($a$$) {alert($a$$)}");
494 }
495
496 public void testDebugFlag3() {
497 args.add("--compilation_level=ADVANCED_OPTIMIZATIONS");
498 args.add("--warning_level=QUIET");
499 args.add("--debug=false");
500 test("function Foo() {}" +
501 "Foo.x = 1;" +
502 "function f() {throw new Foo().x;} f();",
503 "throw (new function() {}).a;");
504 }
505
506 public void testDebugFlag4() {
507 args.add("--compilation_level=ADVANCED_OPTIMIZATIONS");
508 args.add("--warning_level=QUIET");
509 args.add("--debug=true");
510 test("function Foo() {}" +
511 "Foo.x = 1;" +
512 "function f() {throw new Foo().x;} f();",
513 "throw (new function Foo() {}).$x$;");
514 }
515
516 public void testBooleanFlag1() {
517 args.add("--compilation_level=SIMPLE_OPTIMIZATIONS");
518 args.add("--debug");
519 test("function foo(a) {alert(a)}",
520 "function foo($a$$) {alert($a$$)}");
521 }
522
523 public void testBooleanFlag2() {
524 args.add("--debug");
525 args.add("--compilation_level=SIMPLE_OPTIMIZATIONS");
526 test("function foo(a) {alert(a)}",
527 "function foo($a$$) {alert($a$$)}");
528 }
529
530 public void testHelpFlag() {
531 args.add("--help");
532 assertFalse(
533 createCommandLineRunner(
534 new String[] {"function f() {}"}).shouldRunCompiler());
535 }
536
537 public void testExternsLifting1() throws Exception{
538 String code = "/** @externs */ function f() {}";
539 test(new String[] {code},
540 new String[] {});
541
542 assertEquals(2, lastCompiler.getExternsForTesting().size());
543
544 CompilerInput extern = lastCompiler.getExternsForTesting().get(1);
545 assertNull(extern.getModule());
546 assertTrue(extern.isExtern());
547 assertEquals(code, extern.getCode());
548
549 assertEquals(1, lastCompiler.getInputsForTesting().size());
550
551 CompilerInput input = lastCompiler.getInputsForTesting().get(0);
552 assertNotNull(input.getModule());
553 assertFalse(input.isExtern());
554 assertEquals("", input.getCode());
555 }
556
557 public void testExternsLifting2() {
558 args.add("--warning_level=VERBOSE");
559 test(new String[] {"/** @externs */ function f() {}", "f(3);"},
560 new String[] {"f(3);"},
561 TypeCheck.WRONG_ARGUMENT_COUNT);
562 }
563
564 public void testSourceSortingOff() {
565 args.add("--compilation_level=WHITESPACE_ONLY");
566 testSame(
567 new String[] {
568 "goog.require('beer');",
569 "goog.provide('beer');"
570 });
571 }
572
573 public void testSourceSortingOn() {
574 test(new String[] {
575 "goog.require('beer');",
576 "goog.provide('beer');"
577 },
578 new String[] {
579 "var beer = {};",
580 ""
581 });
582 }
583
584 public void testSourceSortingOn2() {
585 test(new String[] {
586 "goog.provide('a');",
587 "goog.require('a');\n" +
588 "var COMPILED = false;",
589 },
590 new String[] {
591 "var a={};",
592 "var COMPILED=!1"
593 });
594 }
595
596 public void testSourceSortingOn3() {
597 args.add("--manage_closure_dependencies=true");
598 test(new String[] {
599 "goog.addDependency('sym', [], []);\nvar x = 3;",
600 "var COMPILED = false;",
601 },
602 new String[] {
603 "var COMPILED = !1;",
604 "var x = 3;"
605 });
606 }
607
608 public void testSourceSortingCircularDeps1() {
609 args.add("--manage_closure_dependencies=true");
610 test(new String[] {
611 "goog.provide('gin'); goog.require('tonic'); var gin = {};",
612 "goog.provide('tonic'); goog.require('gin'); var tonic = {};",
613 "goog.require('gin'); goog.require('tonic');"
614 },
615 JSModule.CIRCULAR_DEPENDENCY_ERROR);
616 }
617
618 public void testSourceSortingCircularDeps2() {
619 args.add("--manage_closure_dependencies=true");
620 test(new String[] {
621 "goog.provide('roses.lime.juice');",
622 "goog.provide('gin'); goog.require('tonic'); var gin = {};",
623 "goog.provide('tonic'); goog.require('gin'); var tonic = {};",
624 "goog.require('gin'); goog.require('tonic');",
625 "goog.provide('gimlet');" +
626 " goog.require('gin'); goog.require('roses.lime.juice');"
627 },
628 JSModule.CIRCULAR_DEPENDENCY_ERROR);
629 }
630
631 public void testSourcePruningOn1() {
632 args.add("--manage_closure_dependencies=true");
633 test(new String[] {
634 "goog.require('beer');",
635 "goog.provide('beer');",
636 "goog.provide('scotch'); var x = 3;"
637 },
638 new String[] {
639 "var beer = {};",
640 ""
641 });
642 }
643
644 public void testSourcePruningOn2() {
645 args.add("--closure_entry_point=guinness");
646 test(new String[] {
647 "goog.provide('guinness');\ngoog.require('beer');",
648 "goog.provide('beer');",
649 "goog.provide('scotch'); var x = 3;"
650 },
651 new String[] {
652 "var beer = {};",
653 "var guinness = {};"
654 });
655 }
656
657 public void testSourcePruningOn3() {
658 args.add("--closure_entry_point=scotch");
659 test(new String[] {
660 "goog.provide('guinness');\ngoog.require('beer');",
661 "goog.provide('beer');",
662 "goog.provide('scotch'); var x = 3;"
663 },
664 new String[] {
665 "var scotch = {}, x = 3;",
666 });
667 }
668
669 public void testSourcePruningOn4() {
670 args.add("--closure_entry_point=scotch");
671 args.add("--closure_entry_point=beer");
672 test(new String[] {
673 "goog.provide('guinness');\ngoog.require('beer');",
674 "goog.provide('beer');",
675 "goog.provide('scotch'); var x = 3;"
676 },
677 new String[] {
678 "var beer = {};",
679 "var scotch = {}, x = 3;",
680 });
681 }
682
683 public void testSourcePruningOn5() {
684 args.add("--closure_entry_point=shiraz");
685 test(new String[] {
686 "goog.provide('guinness');\ngoog.require('beer');",
687 "goog.provide('beer');",
688 "goog.provide('scotch'); var x = 3;"
689 },
690 Compiler.MISSING_ENTRY_ERROR);
691 }
692
693 public void testSourcePruningOn6() {
694 args.add("--closure_entry_point=scotch");
695 test(new String[] {
696 "goog.require('beer');",
697 "goog.provide('beer');",
698 "goog.provide('scotch'); var x = 3;"
699 },
700 new String[] {
701 "var beer = {};",
702 "",
703 "var scotch = {}, x = 3;",
704 });
705 }
706
707 public void testSourcePruningOn7() {
708 args.add("--manage_closure_dependencies=true");
709 test(new String[] {
710 "var COMPILED = false;",
711 },
712 new String[] {
713 "var COMPILED = !1;",
714 });
715 }
716
717 public void testSourcePruningOn8() {
718 args.add("--only_closure_dependencies");
719 args.add("--closure_entry_point=scotch");
720 args.add("--warning_level=VERBOSE");
721 test(new String[] {
722 "/** @externs */\n" +
723 "var externVar;",
724 "goog.provide('scotch'); var x = externVar;"
725 },
726 new String[] {
727 "var scotch = {}, x = externVar;",
728 });
729 }
730
731 public void testModuleEntryPoint() throws Exception {
732 useModules = ModulePattern.STAR;
733 args.add("--only_closure_dependencies");
734 args.add("--closure_entry_point=m1:a");
735 test(
736 new String[] {
737 "goog.provide('a');",
738 "goog.provide('b');"
739 },
740 // Check that 'b' was stripped out, and 'a' was moved to the second
741 // module (m1).
742 new String[] {
743 "",
744 "var a = {};"
745 });
746 }
747
748 public void testNoCompile() {
749 args.add("--warning_level=VERBOSE");
750 test(new String[] {
751 "/** @nocompile */\n" +
752 "goog.provide('x');\n" +
753 "var dupeVar;",
754 "var dupeVar;"
755 },
756 new String[] {
757 "var dupeVar;"
758 });
759 }
760
761 public void testDependencySortingWhitespaceMode() {
762 args.add("--manage_closure_dependencies");
763 args.add("--compilation_level=WHITESPACE_ONLY");
764 test(new String[] {
765 "goog.require('beer');",
766 "goog.provide('beer');\ngoog.require('hops');",
767 "goog.provide('hops');",
768 },
769 new String[] {
770 "goog.provide('hops');",
771 "goog.provide('beer');\ngoog.require('hops');",
772 "goog.require('beer');"
773 });
774 }
775
776 public void testForwardDeclareDroppedTypes() {
777 args.add("--manage_closure_dependencies=true");
778
779 args.add("--warning_level=VERBOSE");
780 test(new String[] {
781 "goog.require('beer');",
782 "goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}",
783 "goog.provide('Scotch'); var x = 3;"
784 },
785 new String[] {
786 "var beer = {}; function f(a) {}",
787 ""
788 });
789
790 test(new String[] {
791 "goog.require('beer');",
792 "goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}"
793 },
794 new String[] {
795 "var beer = {}; function f(a) {}",
796 ""
797 },
798 RhinoErrorReporter.TYPE_PARSE_ERROR);
799 }
800
801 public void testOnlyClosureDependenciesEmptyEntryPoints() throws Exception {
802 // Prevents this from trying to load externs.zip
803 args.add("--use_only_custom_externs=true");
804
805 args.add("--only_closure_dependencies=true");
806 try {
807 CommandLineRunner runner = createCommandLineRunner(new String[0]);
808 runner.doRun();
809 fail("Expected FlagUsageException");
810 } catch (FlagUsageException e) {
811 assertTrue(e.getMessage(),
812 e.getMessage().contains("only_closure_dependencies"));
813 }
814 }
815
816 public void testOnlyClosureDependenciesOneEntryPoint() throws Exception {
817 args.add("--only_closure_dependencies=true");
818 args.add("--closure_entry_point=beer");
819 test(new String[] {
820 "goog.require('beer'); var beerRequired = 1;",
821 "goog.provide('beer');\ngoog.require('hops');\nvar beerProvided = 1;",
822 "goog.provide('hops'); var hopsProvided = 1;",
823 "goog.provide('scotch'); var scotchProvided = 1;",
824 "goog.require('scotch');\nvar includeFileWithoutProvides = 1;",
825 "/** This is base.js */\nvar COMPILED = false;",
826 },
827 new String[] {
828 "var COMPILED = !1;",
829 "var hops = {}, hopsProvided = 1;",
830 "var beer = {}, beerProvided = 1;"
831 });
832 }
833
834 public void testSourceMapExpansion1() {
835 args.add("--js_output_file");
836 args.add("/path/to/out.js");
837 args.add("--create_source_map=%outname%.map");
838 testSame("var x = 3;");
839 assertEquals("/path/to/out.js.map",
840 lastCommandLineRunner.expandSourceMapPath(
841 lastCompiler.getOptions(), null));
842 }
843
844 public void testSourceMapExpansion2() {
845 useModules = ModulePattern.CHAIN;
846 args.add("--create_source_map=%outname%.map");
847 args.add("--module_output_path_prefix=foo");
848 testSame(new String[] {"var x = 3;", "var y = 5;"});
849 assertEquals("foo.map",
850 lastCommandLineRunner.expandSourceMapPath(
851 lastCompiler.getOptions(), null));
852 }
853
854 public void testSourceMapExpansion3() {
855 useModules = ModulePattern.CHAIN;
856 args.add("--create_source_map=%outname%.map");
857 args.add("--module_output_path_prefix=foo_");
858 testSame(new String[] {"var x = 3;", "var y = 5;"});
859 assertEquals("foo_m0.js.map",
860 lastCommandLineRunner.expandSourceMapPath(
861 lastCompiler.getOptions(),
862 lastCompiler.getModuleGraph().getRootModule()));
863 }
864
865 public void testSourceMapFormat1() {
866 args.add("--js_output_file");
867 args.add("/path/to/out.js");
868 testSame("var x = 3;");
869 assertEquals(SourceMap.Format.DEFAULT,
870 lastCompiler.getOptions().sourceMapFormat);
871 }
872
873 public void testSourceMapFormat2() {
874 args.add("--js_output_file");
875 args.add("/path/to/out.js");
876 args.add("--source_map_format=V3");
877 testSame("var x = 3;");
878 assertEquals(SourceMap.Format.V3,
879 lastCompiler.getOptions().sourceMapFormat);
880 }
881
882 public void testModuleWrapperBaseNameExpansion() throws Exception {
883 useModules = ModulePattern.CHAIN;
884 args.add("--module_wrapper=m0:%s // %basename%");
885 testSame(new String[] {
886 "var x = 3;",
887 "var y = 4;"
888 });
889
890 StringBuilder builder = new StringBuilder();
891 lastCommandLineRunner.writeModuleOutput(
892 builder,
893 lastCompiler.getModuleGraph().getRootModule());
894 assertEquals("var x=3; // m0.js\n", builder.toString());
895 }
896
897 public void testCharSetExpansion() {
898 testSame("");
899 assertEquals("US-ASCII", lastCompiler.getOptions().outputCharset);
900 args.add("--charset=UTF-8");
901 testSame("");
902 assertEquals("UTF-8", lastCompiler.getOptions().outputCharset);
903 }
904
905 public void testChainModuleManifest() throws Exception {
906 useModules = ModulePattern.CHAIN;
907 testSame(new String[] {
908 "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"});
909
910 StringBuilder builder = new StringBuilder();
911 lastCommandLineRunner.printModuleGraphManifestOrBundleTo(
912 lastCompiler.getModuleGraph(), builder, true);
913 assertEquals(
914 "{m0}\n" +
915 "i0\n" +
916 "\n" +
917 "{m1:m0}\n" +
918 "i1\n" +
919 "\n" +
920 "{m2:m1}\n" +
921 "i2\n" +
922 "\n" +
923 "{m3:m2}\n" +
924 "i3\n",
925 builder.toString());
926 }
927
928 public void testStarModuleManifest() throws Exception {
929 useModules = ModulePattern.STAR;
930 testSame(new String[] {
931 "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"});
932
933 StringBuilder builder = new StringBuilder();
934 lastCommandLineRunner.printModuleGraphManifestOrBundleTo(
935 lastCompiler.getModuleGraph(), builder, true);
936 assertEquals(
937 "{m0}\n" +
938 "i0\n" +
939 "\n" +
940 "{m1:m0}\n" +
941 "i1\n" +
942 "\n" +
943 "{m2:m0}\n" +
944 "i2\n" +
945 "\n" +
946 "{m3:m0}\n" +
947 "i3\n",
948 builder.toString());
949 }
950
951 public void testOutputModuleGraphJson() throws Exception {
952 useModules = ModulePattern.STAR;
953 testSame(new String[] {
954 "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"});
955
956 StringBuilder builder = new StringBuilder();
957 lastCommandLineRunner.printModuleGraphJsonTo(builder);
958 assertTrue(builder.toString().indexOf("transitive-dependencies") != -1);
959 }
960
961 public void testVersionFlag() {
962 args.add("--version");
963 testSame("");
964 assertEquals(
965 0,
966 new String(errReader.toByteArray()).indexOf(
967 "Closure Compiler (http://code.google.com/closure/compiler)\n" +
968 "Version: "));
969 }
970
971 public void testVersionFlag2() {
972 lastArg = "--version";
973 testSame("");
974 assertEquals(
975 0,
976 new String(errReader.toByteArray()).indexOf(
977 "Closure Compiler (http://code.google.com/closure/compiler)\n" +
978 "Version: "));
979 }
980
981 public void testPrintAstFlag() {
982 args.add("--print_ast=true");
983 testSame("");
984 assertEquals(
985 "digraph AST {\n" +
986 " node [color=lightblue2, style=filled];\n" +
987 " node0 [label=\"BLOCK\"];\n" +
988 " node1 [label=\"SCRIPT\"];\n" +
989 " node0 -> node1 [weight=1];\n" +
990 " node1 -> RETURN [label=\"UNCOND\", " +
991 "fontcolor=\"red\", weight=0.01, color=\"red\"];\n" +
992 " node0 -> RETURN [label=\"SYN_BLOCK\", " +
993 "fontcolor=\"red\", weight=0.01, color=\"red\"];\n" +
994 " node0 -> node1 [label=\"UNCOND\", " +
995 "fontcolor=\"red\", weight=0.01, color=\"red\"];\n" +
996 "}\n\n",
997 new String(outReader.toByteArray()));
998 }
999
1000 public void testSyntheticExterns() {
1001 externs = ImmutableList.of(
1002 SourceFile.fromCode("externs", "myVar.property;"));
1003 test("var theirVar = {}; var myVar = {}; var yourVar = {};",
1004 VarCheck.UNDEFINED_EXTERN_VAR_ERROR);
1005
1006 args.add("--jscomp_off=externsValidation");
1007 args.add("--warning_level=VERBOSE");
1008 test("var theirVar = {}; var myVar = {}; var yourVar = {};",
1009 "var theirVar={},myVar={},yourVar={};");
1010
1011 args.add("--jscomp_off=externsValidation");
1012 args.add("--warning_level=VERBOSE");
1013 test("var theirVar = {}; var myVar = {}; var myVar = {};",
1014 SyntacticScopeCreator.VAR_MULTIPLY_DECLARED_ERROR);
1015 }
1016
1017 public void testGoogAssertStripping() {
1018 args.add("--compilation_level=ADVANCED_OPTIMIZATIONS");
1019 test("goog.asserts.assert(false)",
1020 "");
1021 args.add("--debug");
1022 test("goog.asserts.assert(false)", "goog.$asserts$.$assert$(!1)");
1023 }
1024
1025 public void testMissingReturnCheckOnWithVerbose() {
1026 args.add("--warning_level=VERBOSE");
1027 test("/** @return {number} */ function f() {f()} f();",
1028 CheckMissingReturn.MISSING_RETURN_STATEMENT);
1029 }
1030
1031 public void testGenerateExports() {
1032 args.add("--generate_exports=true");
1033 test("/** @export */ foo.prototype.x = function() {};",
1034 "foo.prototype.x=function(){};"+
1035 "goog.exportSymbol(\"foo.prototype.x\",foo.prototype.x);");
1036 }
1037
1038 public void testDepreciationWithVerbose() {
1039 args.add("--warning_level=VERBOSE");
1040 test("/** @deprecated */ function f() {}; f()",
1041 CheckAccessControls.DEPRECATED_NAME);
1042 }
1043
1044 public void testTwoParseErrors() {
1045 // If parse errors are reported in different files, make
1046 // sure all of them are reported.
1047 Compiler compiler = compile(new String[] {
1048 "var a b;",
1049 "var b c;"
1050 });
1051 assertEquals(2, compiler.getErrors().length);
1052 }
1053
1054 public void testES3ByDefault() {
1055 test("var x = f.function", RhinoErrorReporter.PARSE_ERROR);
1056 }
1057
1058 public void testES5ChecksByDefault() {
1059 testSame("var x = 3; delete x;");
1060 }
1061
1062 public void testES5ChecksInVerbose() {
1063 args.add("--warning_level=VERBOSE");
1064 test("function f(x) { delete x; }", StrictModeCheck.DELETE_VARIABLE);
1065 }
1066
1067 public void testES5() {
1068 args.add("--language_in=ECMASCRIPT5");
1069 test("var x = f.function", "var x = f.function");
1070 test("var let", "var let");
1071 }
1072
1073 public void testES5Strict() {
1074 args.add("--language_in=ECMASCRIPT5_STRICT");
1075 test("var x = f.function", "'use strict';var x = f.function");
1076 test("var let", RhinoErrorReporter.PARSE_ERROR);
1077 test("function f(x) { delete x; }", StrictModeCheck.DELETE_VARIABLE);
1078 }
1079
1080 public void testES5StrictUseStrict() {
1081 args.add("--language_in=ECMASCRIPT5_STRICT");
1082 Compiler compiler = compile(new String[] {"var x = f.function"});
1083 String outputSource = compiler.toSource();
1084 assertEquals("'use strict'", outputSource.substring(0, 12));
1085 }
1086
1087 public void testES5StrictUseStrictMultipleInputs() {
1088 args.add("--language_in=ECMASCRIPT5_STRICT");
1089 Compiler compiler = compile(new String[] {"var x = f.function",
1090 "var y = f.function", "var z = f.function"});
1091 String outputSource = compiler.toSource();
1092 assertEquals("'use strict'", outputSource.substring(0, 12));
1093 assertEquals(outputSource.substring(13).indexOf("'use strict'"), -1);
1094 }
1095
1096 public void testWithKeywordDefault() {
1097 test("var x = {}; with (x) {}", ControlStructureCheck.USE_OF_WITH);
1098 }
1099
1100 public void testWithKeywordWithEs5ChecksOff() {
1101 args.add("--jscomp_off=es5Strict");
1102 testSame("var x = {}; with (x) {}");
1103 }
1104
1105 public void testNoSrCFilesWithManifest() throws IOException {
1106 args.add("--use_only_custom_externs=true");
1107 args.add("--output_manifest=test.MF");
1108 CommandLineRunner runner = createCommandLineRunner(new String[0]);
1109 String expectedMessage = "";
1110 try {
1111 runner.doRun();
1112 } catch (FlagUsageException e) {
1113 expectedMessage = e.getMessage();
1114 }
1115 assertEquals(expectedMessage, "Bad --js flag. " +
1116 "Manifest files cannot be generated when the input is from stdin.");
1117 }
1118
1119 public void testTransformAMD() {
1120 args.add("--transform_amd_modules");
1121 test("define({test: 1})", "exports = {test: 1}");
1122 }
1123
1124 public void testProcessCJS() {
1125 useStringComparison = true;
1126 args.add("--process_common_js_modules");
1127 args.add("--common_js_entry_module=foo/bar");
1128 setFilename(0, "foo/bar.js");
1129 String expected = "var module$foo$bar={test:1};";
1130 test("exports.test = 1", expected);
1131 assertEquals(expected + "\n", outReader.toString());
1132 }
1133
1134 public void testProcessCJSWithModuleOutput() {
1135 useStringComparison = true;
1136 args.add("--process_common_js_modules");
1137 args.add("--common_js_entry_module=foo/bar");
1138 args.add("--module=auto");
1139 setFilename(0, "foo/bar.js");
1140 test("exports.test = 1",
1141 "var module$foo$bar={test:1};");
1142 // With modules=auto no direct output is created.
1143 assertEquals("", outReader.toString());
1144 }
1145
1146 public void testFormattingSingleQuote() {
1147 testSame("var x = '';");
1148 assertEquals("var x=\"\";", lastCompiler.toSource());
1149
1150 args.add("--formatting=SINGLE_QUOTES");
1151 testSame("var x = '';");
1152 assertEquals("var x='';", lastCompiler.toSource());
1153 }
1154
1155 public void testTransformAMDAndProcessCJS() {
1156 useStringComparison = true;
1157 args.add("--transform_amd_modules");
1158 args.add("--process_common_js_modules");
1159 args.add("--common_js_entry_module=foo/bar");
1160 setFilename(0, "foo/bar.js");
1161 test("define({foo: 1})",
1162 "var module$foo$bar={},module$foo$bar={foo:1};");
1163 }
1164
1165 public void testModuleJSON() {
1166 useStringComparison = true;
1167 args.add("--transform_amd_modules");
1168 args.add("--process_common_js_modules");
1169 args.add("--common_js_entry_module=foo/bar");
1170 args.add("--output_module_dependencies=test.json");
1171 setFilename(0, "foo/bar.js");
1172 test("define({foo: 1})",
1173 "var module$foo$bar={},module$foo$bar={foo:1};");
1174 }
1175
1176 public void testOutputSameAsInput() {
1177 args.add("--js_output_file=" + getFilename(0));
1178 test("", AbstractCommandLineRunner.OUTPUT_SAME_AS_INPUT_ERROR);
1179 }
1180
1181 /* Helper functions */
1182
1183 private void testSame(String original) {
1184 testSame(new String[] { original });
1185 }
1186
1187 private void testSame(String[] original) {
1188 test(original, original);
1189 }
1190
1191 private void test(String original, String compiled) {
1192 test(new String[] { original }, new String[] { compiled });
1193 }
1194
1195 /**
1196 * Asserts that when compiling with the given compiler options,
1197 * {@code original} is transformed into {@code compiled}.
1198 */
1199 private void test(String[] original, String[] compiled) {
1200 test(original, compiled, null);
1201 }
1202
1203 /**
1204 * Asserts that when compiling with the given compiler options,
1205 * {@code original} is transformed into {@code compiled}.
1206 * If {@code warning} is non-null, we will also check if the given
1207 * warning type was emitted.
1208 */
1209 private void test(String[] original, String[] compiled,
1210 DiagnosticType warning) {
1211 Compiler compiler = compile(original);
1212
1213 if (warning == null) {
1214 assertEquals("Expected no warnings or errors\n" +
1215 "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) +
1216 "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()),
1217 0, compiler.getErrors().length + compiler.getWarnings().length);
1218 } else {
1219 assertEquals(1, compiler.getWarnings().length);
1220 assertEquals(warning, compiler.getWarnings()[0].getType());
1221 }
1222
1223 Node root = compiler.getRoot().getLastChild();
1224 if (useStringComparison) {
1225 assertEquals(Joiner.on("").join(compiled), compiler.toSource());
1226 } else {
1227 Node expectedRoot = parse(compiled);
1228 String explanation = expectedRoot.checkTreeEquals(root);
1229 assertNull("\nExpected: " + compiler.toSource(expectedRoot) +
1230 "\nResult: " + compiler.toSource(root) +
1231 "\n" + explanation, explanation);
1232 }
1233 }
1234
1235 /**
1236 * Asserts that when compiling, there is an error or warning.
1237 */
1238 private void test(String original, DiagnosticType warning) {
1239 test(new String[] { original }, warning);
1240 }
1241
1242 private void test(String original, String expected, DiagnosticType warning) {
1243 test(new String[] { original }, new String[] { expected }, warning);
1244 }
1245
1246 /**
1247 * Asserts that when compiling, there is an error or warning.
1248 */
1249 private void test(String[] original, DiagnosticType warning) {
1250 Compiler compiler = compile(original);
1251 assertEquals("Expected exactly one warning or error " +
1252 "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) +
1253 "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()),
1254 1, compiler.getErrors().length + compiler.getWarnings().length);
1255
1256 assertTrue(exitCodes.size() > 0);
1257 int lastExitCode = exitCodes.get(exitCodes.size() - 1);
1258
1259 if (compiler.getErrors().length > 0) {
1260 assertEquals(1, compiler.getErrors().length);
1261 assertEquals(warning, compiler.getErrors()[0].getType());
1262 assertEquals(1, lastExitCode);
1263 } else {
1264 assertEquals(1, compiler.getWarnings().length);
1265 assertEquals(warning, compiler.getWarnings()[0].getType());
1266 assertEquals(0, lastExitCode);
1267 }
1268 }
1269
1270 private CommandLineRunner createCommandLineRunner(String[] original) {
1271 for (int i = 0; i < original.length; i++) {
1272 args.add("--js");
1273 args.add("/path/to/input" + i + ".js");
1274 if (useModules == ModulePattern.CHAIN) {
1275 args.add("--module");
1276 args.add("m" + i + ":1" + (i > 0 ? (":m" + (i - 1)) : ""));
1277 } else if (useModules == ModulePattern.STAR) {
1278 args.add("--module");
1279 args.add("m" + i + ":1" + (i > 0 ? ":m0" : ""));
1280 }
1281 }
1282
1283 if (lastArg != null) {
1284 args.add(lastArg);
1285 }
1286
1287 String[] argStrings = args.toArray(new String[] {});
1288 return new CommandLineRunner(
1289 argStrings,
1290 new PrintStream(outReader),
1291 new PrintStream(errReader));
1292 }
1293
1294 private Compiler compile(String[] original) {
1295 CommandLineRunner runner = createCommandLineRunner(original);
1296 assertTrue(new String(errReader.toByteArray()), runner.shouldRunCompiler());
1297 Supplier<List<SourceFile>> inputsSupplier = null;
1298 Supplier<List<JSModule>> modulesSupplier = null;
1299
1300 if (useModules == ModulePattern.NONE) {
1301 List<SourceFile> inputs = Lists.newArrayList();
1302 for (int i = 0; i < original.length; i++) {
1303 inputs.add(SourceFile.fromCode(getFilename(i), original[i]));
1304 }
1305 inputsSupplier = Suppliers.ofInstance(inputs);
1306 } else if (useModules == ModulePattern.STAR) {
1307 modulesSupplier = Suppliers.<List<JSModule>>ofInstance(
1308 Lists.<JSModule>newArrayList(
1309 CompilerTestCase.createModuleStar(original)));
1310 } else if (useModules == ModulePattern.CHAIN) {
1311 modulesSupplier = Suppliers.<List<JSModule>>ofInstance(
1312 Lists.<JSModule>newArrayList(
1313 CompilerTestCase.createModuleChain(original)));
1314 } else {
1315 throw new IllegalArgumentException("Unknown module type: " + useModules);
1316 }
1317
1318 runner.enableTestMode(
1319 Suppliers.<List<SourceFile>>ofInstance(externs),
1320 inputsSupplier,
1321 modulesSupplier,
1322 new Function<Integer, Boolean>() {
1323 @Override
1324 public Boolean apply(Integer code) {
1325 return exitCodes.add(code);
1326 }
1327 });
1328 runner.run();
1329 lastCompiler = runner.getCompiler();
1330 lastCommandLineRunner = runner;
1331 return lastCompiler;
1332 }
1333
1334 private Node parse(String[] original) {
1335 String[] argStrings = args.toArray(new String[] {});
1336 CommandLineRunner runner = new CommandLineRunner(argStrings);
1337 Compiler compiler = runner.createCompiler();
1338 List<SourceFile> inputs = Lists.newArrayList();
1339 for (int i = 0; i < original.length; i++) {
1340 inputs.add(SourceFile.fromCode(getFilename(i), original[i]));
1341 }
1342 CompilerOptions options = new CompilerOptions();
1343 // ECMASCRIPT5 is the most forgiving.
1344 options.setLanguageIn(LanguageMode.ECMASCRIPT5);
1345 compiler.init(externs, inputs, options);
1346 Node all = compiler.parseInputs();
1347 Preconditions.checkState(compiler.getErrorCount() == 0);
1348 Preconditions.checkNotNull(all);
1349 Node n = all.getLastChild();
1350 return n;
1351 }
1352
1353 private void setFilename(int i, String filename) {
1354 this.filenames.put(i, filename);
1355 }
1356
1357 private String getFilename(int i) {
1358 if (filenames.isEmpty()) {
1359 return "input" + i;
1360 }
1361 return filenames.get(i);
1362 }
1363 }