Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2006 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.Joiner;
20 import com.google.common.base.Preconditions;
21 import com.google.common.base.Predicates;
22 import com.google.common.collect.ImmutableList;
23 import com.google.common.collect.Lists;
24 import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
25 import com.google.javascript.jscomp.type.ReverseAbstractInterpreter;
26 import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter;
27 import com.google.javascript.rhino.Node;
28 import com.google.javascript.rhino.testing.BaseJSTypeTestCase;
29
30 import junit.framework.TestCase;
31
32 import java.io.IOException;
33 import java.util.List;
34
35 /**
36 * <p>Base class for testing JS compiler classes that change
37 * the node tree of a compiled JS input.</p>
38 *
39 * <p>Pulls in shared functionality from different test cases. Also supports
40 * node tree comparison for input and output (instead of string comparison),
41 * which makes it easier to write tests b/c you don't have to get the syntax
42 * exactly correct to the spacing.</p>
43 *
44 */
45 public abstract class CompilerTestCase extends TestCase {
46
47 /** Externs for the test */
48 private final List<SourceFile> externsInputs;
49
50 /** Whether to compare input and output as trees instead of strings */
51 private final boolean compareAsTree;
52
53 /** Whether to parse type info from JSDoc comments */
54 protected boolean parseTypeInfo;
55
56 /** Whether we check warnings without source information. */
57 private boolean allowSourcelessWarnings = false;
58
59 /** True iff closure pass runs before pass being tested. */
60 private boolean closurePassEnabled = false;
61
62 /** True iff type checking pass runs before pass being tested. */
63 private boolean typeCheckEnabled = false;
64
65 /** Error level reported by type checker. */
66 private CheckLevel typeCheckLevel;
67
68 /** Whether the Normalize pass runs before pass being tested. */
69 private boolean normalizeEnabled = false;
70
71 /** Whether the expected JS strings should be normalized. */
72 private boolean normalizeExpected = false;
73
74 /** Whether to check that all line number information is preserved. */
75 private boolean checkLineNumbers = true;
76
77 /** Whether we expect parse warnings in the current test. */
78 private boolean expectParseWarningsThisTest = false;
79
80 /**
81 * An expected symbol table error. Only useful for testing the
82 * symbol table error-handling.
83 */
84 private DiagnosticType expectedSymbolTableError = null;
85
86 /**
87 * Whether the MarkNoSideEffectsCalls pass runs before the pass being tested
88 */
89 private boolean markNoSideEffects = false;
90
91 /** The most recently used Compiler instance. */
92 private Compiler lastCompiler;
93
94 /**
95 * Whether to acceptES5 source.
96 */
97 private boolean acceptES5 = true;
98
99 /**
100 * Whether externs changes should be allowed for this pass.
101 */
102 private boolean allowExternsChanges = false;
103
104 /**
105 * Whether the AST should be validated.
106 */
107 private boolean astValidationEnabled = true;
108
109 private String filename = "testcode";
110
111 /**
112 * Constructs a test.
113 *
114 * @param externs Externs JS as a string
115 * @param compareAsTree True to compare output & expected as a node tree.
116 * 99% of the time you want to compare as a tree. There are a few
117 * special cases where you don't, like if you want to test the code
118 * printing of "unnatural" syntax trees. For example,
119 *
120 * <pre>
121 * IF
122 * IF
123 * STATEMENT
124 * ELSE
125 * STATEMENT
126 * </pre>
127 */
128 protected CompilerTestCase(String externs, boolean compareAsTree) {
129 this.externsInputs = ImmutableList.of(
130 SourceFile.fromCode("externs", externs));
131 this.compareAsTree = compareAsTree;
132 this.parseTypeInfo = false;
133 }
134
135 /**
136 * Constructs a test. Uses AST comparison.
137 * @param externs Externs JS as a string
138 */
139 protected CompilerTestCase(String externs) {
140 this(externs, true);
141 }
142
143 /**
144 * Constructs a test. Uses AST comparison and no externs.
145 */
146 protected CompilerTestCase() {
147 this("", true);
148 }
149
150 @Override protected void tearDown() throws Exception {
151 super.tearDown();
152 expectParseWarningsThisTest = false;
153 }
154
155 /**
156 * Gets the compiler pass instance to use for a test.
157 *
158 * @param compiler The compiler
159 * @return The pass to test
160 */
161 protected abstract CompilerPass getProcessor(Compiler compiler);
162
163
164 /**
165 * Gets the compiler options to use for this test. Use getProcessor to
166 * determine what passes should be run.
167 */
168 protected CompilerOptions getOptions() {
169 return getOptions(new CompilerOptions());
170 }
171
172 /**
173 * Gets the compiler options to use for this test. Use getProcessor to
174 * determine what passes should be run.
175 */
176 protected CompilerOptions getOptions(CompilerOptions options) {
177 if (this.acceptES5) {
178 options.setLanguageIn(LanguageMode.ECMASCRIPT5);
179 }
180
181 // This doesn't affect whether checkSymbols is run--it just affects
182 // whether variable warnings are filtered.
183 options.checkSymbols = true;
184
185 options.setWarningLevel(
186 DiagnosticGroups.MISSING_PROPERTIES, CheckLevel.WARNING);
187 options.setWarningLevel(
188 DiagnosticGroups.INVALID_CASTS, CheckLevel.WARNING);
189 options.setCodingConvention(getCodingConvention());
190 return options;
191 }
192
193 protected CodingConvention getCodingConvention() {
194 return new GoogleCodingConvention();
195 }
196
197 public void setFilename(String filename) {
198 this.filename = filename;
199 }
200
201 /**
202 * Returns the number of times the pass should be run before results are
203 * verified.
204 */
205 protected int getNumRepetitions() {
206 // Since most compiler passes should be idempotent, we run each pass twice
207 // by default.
208 return 2;
209 }
210
211 /** Expect warnings without source information. */
212 void allowSourcelessWarnings() {
213 allowSourcelessWarnings = true;
214 }
215
216 /** The most recently used JSComp instance. */
217 Compiler getLastCompiler() {
218 return lastCompiler;
219 }
220
221 /**
222 * Whether to allow ECMASCRIPT5 source parsing.
223 */
224 protected void enableEcmaScript5(boolean acceptES5) {
225 this.acceptES5 = acceptES5;
226 }
227
228 /**
229 * Whether to allow externs changes.
230 */
231 protected void allowExternsChanges(boolean allowExternsChanges) {
232 this.allowExternsChanges = allowExternsChanges;
233 }
234
235 /**
236 * Perform type checking before running the test pass. This will check
237 * for type errors and annotate nodes with type information.
238 *
239 * @param level the level of severity to report for type errors
240 *
241 * @see TypeCheck
242 */
243 public void enableTypeCheck(CheckLevel level) {
244 typeCheckEnabled = true;
245 typeCheckLevel = level;
246 }
247
248 /**
249 * Check to make sure that line numbers were preserved.
250 */
251 public void enableLineNumberCheck(boolean newVal) {
252 checkLineNumbers = newVal;
253 }
254
255 /**
256 * Do not run type checking before running the test pass.
257 *
258 * @see TypeCheck
259 */
260 void disableTypeCheck() {
261 typeCheckEnabled = false;
262 }
263
264 /**
265 * Process closure library primitives.
266 */
267 // TODO(nicksantos): Fix other passes to use this when appropriate.
268 void enableClosurePass() {
269 closurePassEnabled = true;
270 }
271
272 /**
273 * Perform AST normalization before running the test pass, and anti-normalize
274 * after running it.
275 *
276 * @see Normalize
277 */
278 protected void enableNormalize() {
279 enableNormalize(true);
280 }
281
282 /**
283 * Perform AST normalization before running the test pass, and anti-normalize
284 * after running it.
285 *
286 * @param normalizeExpected Whether to perform normalization on the
287 * expected JS result.
288 * @see Normalize
289 */
290 protected void enableNormalize(boolean normalizeExpected) {
291 normalizeEnabled = true;
292 this.normalizeExpected = normalizeExpected;
293 }
294
295 /**
296 * Don't perform AST normalization before running the test pass.
297 * @see Normalize
298 */
299 protected void disableNormalize() {
300 normalizeEnabled = false;
301 }
302
303 /**
304 * Run the MarkSideEffectCalls pass before running the test pass.
305 *
306 * @see MarkNoSideEffectCalls
307 */
308 void enableMarkNoSideEffects() {
309 markNoSideEffects = true;
310 }
311
312 /**
313 * Whether to allow Validate the AST after each run of the pass.
314 */
315 protected void enableAstValidation(boolean validate) {
316 astValidationEnabled = validate;
317 }
318
319 /** Whether we should ignore parse warnings for the current test method. */
320 protected void setExpectParseWarningsThisTest() {
321 expectParseWarningsThisTest = true;
322 }
323
324 /** Returns a newly created TypeCheck. */
325 private static TypeCheck createTypeCheck(Compiler compiler,
326 CheckLevel level) {
327 ReverseAbstractInterpreter rai =
328 new SemanticReverseAbstractInterpreter(compiler.getCodingConvention(),
329 compiler.getTypeRegistry());
330
331 return new TypeCheck(compiler, rai, compiler.getTypeRegistry(),
332 level, CheckLevel.OFF);
333 }
334
335 /**
336 * Verifies that the compiler pass's JS output matches the expected output.
337 *
338 * @param js Input
339 * @param expected Expected JS output
340 */
341 public void test(String js, String expected) {
342 test(js, expected, (DiagnosticType) null);
343 }
344
345 /**
346 * Verifies that the compiler pass's JS output matches the expected output,
347 * or that an expected error is encountered.
348 *
349 * @param js Input
350 * @param expected Expected output, or null if an error is expected
351 * @param error Expected error, or null if no error is expected
352 */
353 public void test(String js, String expected, DiagnosticType error) {
354 test(js, expected, error, null);
355 }
356
357
358 /**
359 * Verifies that the compiler pass's JS output matches the expected output,
360 * or that an expected error is encountered.
361 *
362 * @param js Input
363 * @param expected Expected output, or null if an error is expected
364 * @param error Expected error, or null if no error is expected
365 * @param warning Expected warning, or null if no warning is expected
366 * @param description The content of the error expected
367 */
368 public void test(String js, String expected, DiagnosticType error,
369 DiagnosticType warning, String description) {
370 test(externsInputs, js, expected, error, warning, description);
371 }
372
373 /**
374 * Verifies that the compiler pass's JS output matches the expected output
375 * and (optionally) that an expected warning is issued. Or, if an error is
376 * expected, this method just verifies that the error is encountered.
377 *
378 * @param js Input
379 * @param expected Expected output, or null if an error is expected
380 * @param error Expected error, or null if no error is expected
381 * @param warning Expected warning, or null if no warning is expected
382 */
383 public void test(String js, String expected,
384 DiagnosticType error, DiagnosticType warning) {
385 test(externsInputs, js, expected, error, warning, null);
386 }
387
388 /**
389 * Verifies that the compiler pass's JS output matches the expected output
390 * and (optionally) that an expected warning is issued. Or, if an error is
391 * expected, this method just verifies that the error is encountered.
392 *
393 * @param externs Externs input
394 * @param js Input
395 * @param expected Expected output, or null if an error is expected
396 * @param error Expected error, or null if no error is expected
397 * @param warning Expected warning, or null if no warning is expected
398 */
399 public void test(String externs, String js, String expected,
400 DiagnosticType error, DiagnosticType warning) {
401 test(externs, js, expected, error, warning, null);
402 }
403
404 /**
405 * Verifies that the compiler pass's JS output matches the expected output
406 * and (optionally) that an expected warning is issued. Or, if an error is
407 * expected, this method just verifies that the error is encountered.
408 *
409 * @param externs Externs input
410 * @param js Input
411 * @param expected Expected output, or null if an error is expected
412 * @param error Expected error, or null if no error is expected
413 * @param warning Expected warning, or null if no warning is expected
414 * @param description The description of the expected warning,
415 * or null if no warning is expected or if the warning's description
416 * should not be examined
417 */
418 public void test(String externs, String js, String expected,
419 DiagnosticType error, DiagnosticType warning,
420 String description) {
421 List<SourceFile> externsInputs = ImmutableList.of(
422 SourceFile.fromCode("externs", externs));
423 test(externsInputs, js, expected, error, warning, description);
424 }
425
426 /**
427 * Verifies that the compiler pass's JS output matches the expected output
428 * and (optionally) that an expected warning is issued. Or, if an error is
429 * expected, this method just verifies that the error is encountered.
430 *
431 * @param externs Externs inputs
432 * @param js Input
433 * @param expected Expected output, or null if an error is expected
434 * @param error Expected error, or null if no error is expected
435 * @param warning Expected warning, or null if no warning is expected
436 * @param description The description of the expected warning,
437 * or null if no warning is expected or if the warning's description
438 * should not be examined
439 */
440 public void test(List<SourceFile> externs, String js, String expected,
441 DiagnosticType error,
442 DiagnosticType warning, String description) {
443 Compiler compiler = createCompiler();
444 lastCompiler = compiler;
445
446 CompilerOptions options = getOptions();
447
448 if (this.acceptES5) {
449 options.setLanguageIn(LanguageMode.ECMASCRIPT5);
450 }
451 // Note that in this context, turning on the checkTypes option won't
452 // actually cause the type check to run.
453 options.checkTypes = parseTypeInfo;
454 compiler.init(externs, ImmutableList.of(
455 SourceFile.fromCode(filename, js)), options);
456
457 BaseJSTypeTestCase.addNativeProperties(compiler.getTypeRegistry());
458
459 test(compiler, maybeCreateArray(expected), error, warning, description);
460 }
461
462 private String[] maybeCreateArray(String expected) {
463 if (expected != null) {
464 return new String[] { expected };
465 }
466 return null;
467 }
468
469 /**
470 * Verifies that the compiler pass's JS output matches the expected output.
471 *
472 * @param js Inputs
473 * @param expected Expected JS output
474 */
475 public void test(String[] js, String[] expected) {
476 test(js, expected, null);
477 }
478
479 /**
480 * Verifies that the compiler pass's JS output matches the expected output,
481 * or that an expected error is encountered.
482 *
483 * @param js Inputs
484 * @param expected Expected JS output
485 * @param error Expected error, or null if no error is expected
486 */
487 public void test(String[] js, String[] expected, DiagnosticType error) {
488 test(js, expected, error, null);
489 }
490
491 /**
492 * Verifies that the compiler pass's JS output matches the expected output
493 * and (optionally) that an expected warning is issued. Or, if an error is
494 * expected, this method just verifies that the error is encountered.
495 *
496 * @param js Inputs
497 * @param expected Expected JS output
498 * @param error Expected error, or null if no error is expected
499 * @param warning Expected warning, or null if no warning is expected
500 */
501 public void test(String[] js, String[] expected, DiagnosticType error,
502 DiagnosticType warning) {
503 test(js, expected, error, warning, null);
504 }
505
506 /**
507 * Verifies that the compiler pass's JS output matches the expected output
508 * and (optionally) that an expected warning is issued. Or, if an error is
509 * expected, this method just verifies that the error is encountered.
510 *
511 * @param js Inputs
512 * @param expected Expected JS output
513 * @param error Expected error, or null if no error is expected
514 * @param warning Expected warning, or null if no warning is expected
515 * @param description The description of the expected warning,
516 * or null if no warning is expected or if the warning's description
517 * should not be examined
518 */
519 public void test(String[] js, String[] expected, DiagnosticType error,
520 DiagnosticType warning, String description) {
521 Compiler compiler = createCompiler();
522 lastCompiler = compiler;
523
524 List<SourceFile> inputs = Lists.newArrayList();
525 for (int i = 0; i < js.length; i++) {
526 inputs.add(SourceFile.fromCode("input" + i, js[i]));
527 }
528 compiler.init(externsInputs, inputs, getOptions());
529 test(compiler, expected, error, warning, description);
530 }
531
532 /**
533 * Verifies that the compiler pass's JS output matches the expected output.
534 *
535 * @param modules Module inputs
536 * @param expected Expected JS outputs (one per module)
537 */
538 public void test(JSModule[] modules, String[] expected) {
539 test(modules, expected, null);
540 }
541
542 /**
543 * Verifies that the compiler pass's JS output matches the expected output,
544 * or that an expected error is encountered.
545 *
546 * @param modules Module inputs
547 * @param expected Expected JS outputs (one per module)
548 * @param error Expected error, or null if no error is expected
549 */
550 public void test(JSModule[] modules, String[] expected,
551 DiagnosticType error) {
552 test(modules, expected, error, null);
553 }
554
555 /**
556 * Verifies that the compiler pass's JS output matches the expected output
557 * and (optionally) that an expected warning is issued. Or, if an error is
558 * expected, this method just verifies that the error is encountered.
559 *
560 * @param modules Module inputs
561 * @param expected Expected JS outputs (one per module)
562 * @param error Expected error, or null if no error is expected
563 * @param warning Expected warning, or null if no warning is expected
564 */
565 public void test(JSModule[] modules, String[] expected,
566 DiagnosticType error, DiagnosticType warning) {
567 Compiler compiler = createCompiler();
568 lastCompiler = compiler;
569
570 compiler.initModules(
571 externsInputs, Lists.newArrayList(modules), getOptions());
572 test(compiler, expected, error, warning);
573 }
574
575 /**
576 * Verifies that the compiler pass's JS output is the same as its input.
577 *
578 * @param js Input and output
579 */
580 public void testSame(String js) {
581 test(js, js);
582 }
583
584 /**
585 * Verifies that the compiler pass's JS output is the same as its input
586 * and (optionally) that an expected warning is issued.
587 *
588 * @param js Input and output
589 * @param warning Expected warning, or null if no warning is expected
590 */
591 public void testSame(String js, DiagnosticType warning) {
592 test(js, js, null, warning);
593 }
594
595 /**
596 * Verifies that the compiler pass's JS output is the same as its input
597 * and (optionally) that an expected warning is issued.
598 *
599 * @param js Input and output
600 * @param diag Expected error or warning, or null if none is expected
601 * @param error true if diag is an error, false if it is a warning
602 */
603 public void testSame(String js, DiagnosticType diag, boolean error) {
604 if (error) {
605 test(js, js, diag);
606 } else {
607 test(js, js, null, diag);
608 }
609 }
610
611 /**
612 * Verifies that the compiler pass's JS output is the same as its input
613 * and (optionally) that an expected warning is issued.
614 *
615 * @param externs Externs input
616 * @param js Input and output
617 * @param warning Expected warning, or null if no warning is expected
618 */
619 public void testSame(String externs, String js, DiagnosticType warning) {
620 testSame(externs, js, warning, null);
621 }
622
623 /**
624 * Verifies that the compiler pass's JS output is the same as its input
625 * and (optionally) that an expected warning is issued.
626 *
627 * @param externs Externs input
628 * @param js Input and output
629 * @param diag Expected error or warning, or null if none is expected
630 * @param error true if diag is an error, false if it is a warning
631 */
632 public void testSame(
633 String externs, String js, DiagnosticType diag, boolean error) {
634 if (error) {
635 test(externs, js, js, diag, null);
636 } else {
637 test(externs, js, js, null, diag);
638 }
639 }
640
641 /**
642 * Verifies that the compiler pass's JS output is the same as its input
643 * and (optionally) that an expected warning and description is issued.
644 *
645 * @param externs Externs input
646 * @param js Input and output
647 * @param warning Expected warning, or null if no warning is expected
648 * @param description The description of the expected warning,
649 * or null if no warning is expected or if the warning's description
650 * should not be examined
651 */
652 public void testSame(String externs, String js, DiagnosticType warning,
653 String description) {
654 List<SourceFile> externsInputs = ImmutableList.of(
655 SourceFile.fromCode("externs", externs));
656 test(externsInputs, js, js, null, warning, description);
657 }
658
659 /**
660 * Verifies that the compiler pass's JS output is the same as its input.
661 *
662 * @param js Inputs and outputs
663 */
664 public void testSame(String[] js) {
665 test(js, js);
666 }
667
668 /**
669 * Verifies that the compiler pass's JS output is the same as its input,
670 * and emits the given error.
671 *
672 * @param js Inputs and outputs
673 * @param error Expected error, or null if no error is expected
674 */
675 public void testSame(String[] js, DiagnosticType error) {
676 test(js, js, error);
677 }
678
679 /**
680 * Verifies that the compiler pass's JS output is the same as its input,
681 * and emits the given error and warning.
682 *
683 * @param js Inputs and outputs
684 * @param error Expected error, or null if no error is expected
685 * @param warning Expected warning, or null if no warning is expected
686 */
687 public void testSame(
688 String[] js, DiagnosticType error, DiagnosticType warning) {
689 test(js, js, error, warning);
690 }
691
692 /**
693 * Verifies that the compiler pass's JS output is the same as the input.
694 *
695 * @param modules Module inputs
696 */
697 public void testSame(JSModule[] modules) {
698 testSame(modules, null);
699 }
700
701 /**
702 * Verifies that the compiler pass's JS output is the same as the input.
703 *
704 * @param modules Module inputs
705 * @param warning A warning, or null for no expected warning.
706 */
707 public void testSame(JSModule[] modules, DiagnosticType warning) {
708 try {
709 String[] expected = new String[modules.length];
710 for (int i = 0; i < modules.length; i++) {
711 expected[i] = "";
712 for (CompilerInput input : modules[i].getInputs()) {
713 expected[i] += input.getSourceFile().getCode();
714 }
715 }
716 test(modules, expected, null, warning);
717 } catch (IOException e) {
718 throw new RuntimeException(e);
719 }
720 }
721
722 /**
723 * Verifies that the compiler pass's JS output matches the expected output
724 * and (optionally) that an expected warning is issued. Or, if an error is
725 * expected, this method just verifies that the error is encountered.
726 *
727 * @param compiler A compiler that has been initialized via
728 * {@link Compiler#init}
729 * @param expected Expected output, or null if an error is expected
730 * @param error Expected error, or null if no error is expected
731 * @param warning Expected warning, or null if no warning is expected
732 */
733 protected void test(Compiler compiler, String[] expected,
734 DiagnosticType error, DiagnosticType warning) {
735 test(compiler, expected, error, warning, null);
736 }
737
738
739 /**
740 * Verifies that the compiler pass's JS output matches the expected output
741 * and (optionally) that an expected warning is issued. Or, if an error is
742 * expected, this method just verifies that the error is encountered.
743 *
744 * @param compiler A compiler that has been initialized via
745 * {@link Compiler#init}
746 * @param expected Expected output, or null if an error is expected
747 * @param error Expected error, or null if no error is expected
748 * @param warning Expected warning, or null if no warning is expected
749 * @param description The description of the expected warning,
750 * or null if no warning is expected or if the warning's description
751 * should not be examined
752 */
753 private void test(Compiler compiler, String[] expected,
754 DiagnosticType error, DiagnosticType warning,
755 String description) {
756 CodeChangeHandler recentChange = new CodeChangeHandler();
757 compiler.addChangeHandler(recentChange);
758
759 Node root = compiler.parseInputs();
760 assertTrue("Unexpected parse error(s): " +
761 Joiner.on("\n").join(compiler.getErrors()), root != null);
762 if (!expectParseWarningsThisTest) {
763 assertTrue("Unexpected parse warnings(s): " +
764 Joiner.on("\n").join(compiler.getWarnings()),
765 compiler.getWarnings().length == 0);
766 }
767
768 if (astValidationEnabled) {
769 (new AstValidator()).validateRoot(root);
770 }
771 Node externsRoot = root.getFirstChild();
772 Node mainRoot = root.getLastChild();
773
774 // Save the tree for later comparison.
775 Node rootClone = root.cloneTree();
776 Node externsRootClone = rootClone.getFirstChild();
777 Node mainRootClone = rootClone.getLastChild();
778
779 int numRepetitions = getNumRepetitions();
780 ErrorManager[] errorManagers = new ErrorManager[numRepetitions];
781 int aggregateWarningCount = 0;
782 List<JSError> aggregateWarnings = Lists.newArrayList();
783 boolean hasCodeChanged = false;
784
785 assertFalse("Code should not change before processing",
786 recentChange.hasCodeChanged());
787
788 for (int i = 0; i < numRepetitions; ++i) {
789 if (compiler.getErrorCount() == 0) {
790 errorManagers[i] = new BlackHoleErrorManager(compiler);
791
792 // Only run process closure primitives once, if asked.
793 if (closurePassEnabled && i == 0) {
794 recentChange.reset();
795 new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR)
796 .process(null, mainRoot);
797 hasCodeChanged = hasCodeChanged || recentChange.hasCodeChanged();
798 }
799
800 // Only run the type checking pass once, if asked.
801 // Running it twice can cause unpredictable behavior because duplicate
802 // objects for the same type are created, and the type system
803 // uses reference equality to compare many types.
804 if (typeCheckEnabled && i == 0) {
805 TypeCheck check = createTypeCheck(compiler, typeCheckLevel);
806 check.processForTesting(externsRoot, mainRoot);
807 }
808
809 // Only run the normalize pass once, if asked.
810 if (normalizeEnabled && i == 0) {
811 normalizeActualCode(compiler, externsRoot, mainRoot);
812 }
813
814 if (markNoSideEffects && i == 0) {
815 MarkNoSideEffectCalls mark = new MarkNoSideEffectCalls(compiler);
816 mark.process(externsRoot, mainRoot);
817 }
818
819 recentChange.reset();
820
821 getProcessor(compiler).process(externsRoot, mainRoot);
822 if (astValidationEnabled) {
823 (new AstValidator()).validateRoot(root);
824 }
825 if (checkLineNumbers) {
826 (new LineNumberCheck(compiler)).process(externsRoot, mainRoot);
827 }
828
829 hasCodeChanged = hasCodeChanged || recentChange.hasCodeChanged();
830 aggregateWarningCount += errorManagers[i].getWarningCount();
831 aggregateWarnings.addAll(Lists.newArrayList(compiler.getWarnings()));
832
833 if (normalizeEnabled) {
834 boolean verifyDeclaredConstants = true;
835 new Normalize.VerifyConstants(compiler, verifyDeclaredConstants)
836 .process(externsRoot, mainRoot);
837 }
838 }
839 }
840
841 if (error == null) {
842 assertEquals(
843 "Unexpected error(s): " + Joiner.on("\n").join(compiler.getErrors()),
844 0, compiler.getErrorCount());
845
846 // Verify the symbol table.
847 ErrorManager symbolTableErrorManager =
848 new BlackHoleErrorManager(compiler);
849 Node expectedRoot = null;
850 if (expected != null) {
851 expectedRoot = parseExpectedJs(expected);
852 expectedRoot.detachFromParent();
853 }
854
855 JSError[] stErrors = symbolTableErrorManager.getErrors();
856 if (expectedSymbolTableError != null) {
857 assertEquals("There should be one error.", 1, stErrors.length);
858 assertEquals(expectedSymbolTableError, stErrors[0].getType());
859 } else {
860 assertEquals("Unexpected symbol table error(s): " +
861 Joiner.on("\n").join(stErrors),
862 0, stErrors.length);
863 }
864
865 if (warning == null) {
866 assertEquals(
867 "Unexpected warning(s): " + Joiner.on("\n").join(aggregateWarnings),
868 0, aggregateWarningCount);
869 } else {
870 assertEquals("There should be one warning, repeated " + numRepetitions +
871 " time(s).", numRepetitions, aggregateWarningCount);
872 for (int i = 0; i < numRepetitions; ++i) {
873 JSError[] warnings = errorManagers[i].getWarnings();
874 JSError actual = warnings[0];
875 assertEquals(warning, actual.getType());
876
877 // Make sure that source information is always provided.
878 if (!allowSourcelessWarnings) {
879 assertTrue("Missing source file name in warning",
880 actual.sourceName != null && !actual.sourceName.isEmpty());
881 assertTrue("Missing line number in warning",
882 -1 != actual.lineNumber);
883 assertTrue("Missing char number in warning",
884 -1 != actual.getCharno());
885 }
886
887 if (description != null) {
888 assertEquals(description, actual.description);
889 }
890 }
891 }
892
893 // If we ran normalize on the AST, we must also run normalize on the
894 // clone before checking for changes.
895 if (normalizeEnabled) {
896 normalizeActualCode(compiler, externsRootClone, mainRootClone);
897 }
898
899 boolean codeChange = !mainRootClone.isEquivalentTo(mainRoot);
900 boolean externsChange = !externsRootClone.isEquivalentTo(externsRoot);
901
902 // Generally, externs should not be change by the compiler passes.
903 if (externsChange && !allowExternsChanges) {
904 String explanation = externsRootClone.checkTreeEquals(externsRoot);
905 fail("Unexpected changes to externs" +
906 "\nExpected: " + compiler.toSource(externsRootClone) +
907 "\nResult: " + compiler.toSource(externsRoot) +
908 "\n" + explanation);
909 }
910
911 if (!codeChange && !externsChange) {
912 assertFalse(
913 "compiler.reportCodeChange() was called " +
914 "even though nothing changed",
915 hasCodeChanged);
916 } else {
917 assertTrue("compiler.reportCodeChange() should have been called",
918 hasCodeChanged);
919 }
920
921 if (expected != null) {
922 if (compareAsTree) {
923 String explanation = expectedRoot.checkTreeEquals(mainRoot);
924 assertNull("\nExpected: " + compiler.toSource(expectedRoot) +
925 "\nResult: " + compiler.toSource(mainRoot) +
926 "\n" + explanation, explanation);
927 } else if (expected != null) {
928 assertEquals(
929 Joiner.on("").join(expected), compiler.toSource(mainRoot));
930 }
931 }
932
933 // Verify normalization is not invalidated.
934 Node normalizeCheckRootClone = root.cloneTree();
935 Node normalizeCheckExternsRootClone = normalizeCheckRootClone.getFirstChild();
936 Node normalizeCheckMainRootClone = normalizeCheckRootClone.getLastChild();
937 new PrepareAst(compiler).process(
938 normalizeCheckExternsRootClone, normalizeCheckMainRootClone);
939 String explanation =
940 normalizeCheckMainRootClone.checkTreeEquals(mainRoot);
941 assertNull("Node structure normalization invalidated.\nExpected: " +
942 compiler.toSource(normalizeCheckMainRootClone) +
943 "\nResult: " + compiler.toSource(mainRoot) +
944 "\n" + explanation, explanation);
945
946 // TODO(johnlenz): enable this for most test cases.
947 // Currently, this invalidates test for while-loops, for-loop
948 // initializers, and other naming. However, a set of code
949 // (Closure primitive rewrites, etc) runs before the Normalize pass,
950 // so this can't be force on everywhere.
951 if (normalizeEnabled) {
952 new Normalize(compiler, true).process(
953 normalizeCheckExternsRootClone, normalizeCheckMainRootClone);
954 explanation = normalizeCheckMainRootClone.checkTreeEquals(mainRoot);
955 assertNull("Normalization invalidated.\nExpected: " +
956 compiler.toSource(normalizeCheckMainRootClone) +
957 "\nResult: " + compiler.toSource(mainRoot) +
958 "\n" + explanation, explanation);
959 }
960 } else {
961 String errors = "";
962 for (JSError actualError : compiler.getErrors()) {
963 errors += actualError.description + "\n";
964 }
965 assertEquals("There should be one error. " + errors,
966 1, compiler.getErrorCount());
967 assertEquals(errors, error, compiler.getErrors()[0].getType());
968
969 if (warning != null) {
970 String warnings = "";
971 for (JSError actualError : compiler.getWarnings()) {
972 warnings += actualError.description + "\n";
973 }
974 assertEquals("There should be one warning. " + warnings,
975 1, compiler.getWarningCount());
976 assertEquals(warnings, warning, compiler.getWarnings()[0].getType());
977 }
978 }
979 }
980
981 private void normalizeActualCode(
982 Compiler compiler, Node externsRoot, Node mainRoot) {
983 Normalize normalize = new Normalize(compiler, false);
984 normalize.process(externsRoot, mainRoot);
985 }
986
987 /**
988 * Parses expected JS inputs and returns the root of the parse tree.
989 */
990 protected Node parseExpectedJs(String[] expected) {
991 Compiler compiler = createCompiler();
992 List<SourceFile> inputs = Lists.newArrayList();
993 for (int i = 0; i < expected.length; i++) {
994 inputs.add(SourceFile.fromCode("expected" + i, expected[i]));
995 }
996 compiler.init(externsInputs, inputs, getOptions());
997 Node root = compiler.parseInputs();
998 assertTrue("Unexpected parse error(s): " +
999 Joiner.on("\n").join(compiler.getErrors()), root != null);
1000 Node externsRoot = root.getFirstChild();
1001 Node mainRoot = externsRoot.getNext();
1002 // Only run the normalize pass, if asked.
1003 if (normalizeEnabled && normalizeExpected && !compiler.hasErrors()) {
1004 Normalize normalize = new Normalize(compiler, false);
1005 normalize.process(externsRoot, mainRoot);
1006 }
1007 return mainRoot;
1008 }
1009
1010 protected Node parseExpectedJs(String expected) {
1011 return parseExpectedJs(new String[] {expected});
1012 }
1013
1014 /**
1015 * Generates a list of modules from a list of inputs, such that each module
1016 * depends on the module before it.
1017 */
1018 static JSModule[] createModuleChain(String... inputs) {
1019 JSModule[] modules = createModules(inputs);
1020 for (int i = 1; i < modules.length; i++) {
1021 modules[i].addDependency(modules[i - 1]);
1022 }
1023 return modules;
1024 }
1025
1026 /**
1027 * Generates a list of modules from a list of inputs, such that each module
1028 * depends on the first module.
1029 */
1030 static JSModule[] createModuleStar(String... inputs) {
1031 JSModule[] modules = createModules(inputs);
1032 for (int i = 1; i < modules.length; i++) {
1033 modules[i].addDependency(modules[0]);
1034 }
1035 return modules;
1036 }
1037
1038 /**
1039 * Generates a list of modules from a list of inputs, such that modules
1040 * form a bush formation. In a bush formation, module 2 depends
1041 * on module 1, and all other modules depend on module 2.
1042 */
1043 static JSModule[] createModuleBush(String ... inputs) {
1044 Preconditions.checkState(inputs.length > 2);
1045 JSModule[] modules = createModules(inputs);
1046 for (int i = 1; i < modules.length; i++) {
1047 modules[i].addDependency(modules[i == 1 ? 0 : 1]);
1048 }
1049 return modules;
1050 }
1051
1052 /**
1053 * Generates a list of modules from a list of inputs, such that modules
1054 * form a tree formation. In a tree formation, module N depends on
1055 * module `floor(N/2)`, So the modules form a balanced binary tree.
1056 */
1057 static JSModule[] createModuleTree(String ... inputs) {
1058 JSModule[] modules = createModules(inputs);
1059 for (int i = 1; i < modules.length; i++) {
1060 modules[i].addDependency(modules[(i - 1) / 2]);
1061 }
1062 return modules;
1063 }
1064
1065 /**
1066 * Generates a list of modules from a list of inputs. Does not generate any
1067 * dependencies between the modules.
1068 */
1069 static JSModule[] createModules(String... inputs) {
1070 JSModule[] modules = new JSModule[inputs.length];
1071 for (int i = 0; i < inputs.length; i++) {
1072 JSModule module = modules[i] = new JSModule("m" + i);
1073 module.add(SourceFile.fromCode("i" + i, inputs[i]));
1074 }
1075 return modules;
1076 }
1077
1078 private static class BlackHoleErrorManager extends BasicErrorManager {
1079 private BlackHoleErrorManager(Compiler compiler) {
1080 compiler.setErrorManager(this);
1081 }
1082
1083 @Override
1084 public void println(CheckLevel level, JSError error) {}
1085
1086 @Override
1087 public void printSummary() {}
1088 }
1089
1090 Compiler createCompiler() {
1091 Compiler compiler = new Compiler();
1092 return compiler;
1093 }
1094
1095 protected void setExpectedSymbolTableError(DiagnosticType type) {
1096 this.expectedSymbolTableError = type;
1097 }
1098
1099 /** Finds the first matching qualified name node in post-traversal order. */
1100 protected final Node findQualifiedNameNode(final String name, Node root) {
1101 final List<Node> matches = Lists.newArrayList();
1102 NodeUtil.visitPostOrder(root,
1103 new NodeUtil.Visitor() {
1104 @Override public void visit(Node n) {
1105 if (name.equals(n.getQualifiedName())) {
1106 matches.add(n);
1107 }
1108 }
1109 },
1110 Predicates.<Node>alwaysTrue());
1111 return matches.get(0);
1112 }
1113 }