File: CompilerTestCase.java

package info (click to toggle)
closure-compiler 20130227%2Bdfsg1-10
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 12,776 kB
  • ctags: 45,946
  • sloc: java: 175,338; xml: 371; makefile: 19; sh: 6
file content (1113 lines) | stat: -rw-r--r-- 38,194 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
/*
 * Copyright 2006 The Closure Compiler Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.javascript.jscomp;

import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import com.google.javascript.jscomp.type.ReverseAbstractInterpreter;
import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.testing.BaseJSTypeTestCase;

import junit.framework.TestCase;

import java.io.IOException;
import java.util.List;

/**
 * <p>Base class for testing JS compiler classes that change
 * the node tree of a compiled JS input.</p>
 *
 * <p>Pulls in shared functionality from different test cases. Also supports
 * node tree comparison for input and output (instead of string comparison),
 * which makes it easier to write tests b/c you don't have to get the syntax
 * exactly correct to the spacing.</p>
 *
 */
public abstract class CompilerTestCase extends TestCase  {

  /** Externs for the test */
  private final List<SourceFile> externsInputs;

  /** Whether to compare input and output as trees instead of strings */
  private final boolean compareAsTree;

  /** Whether to parse type info from JSDoc comments */
  protected boolean parseTypeInfo;

  /** Whether we check warnings without source information. */
  private boolean allowSourcelessWarnings = false;

  /** True iff closure pass runs before pass being tested. */
  private boolean closurePassEnabled = false;

  /** True iff type checking pass runs before pass being tested. */
  private boolean typeCheckEnabled = false;

  /** Error level reported by type checker. */
  private CheckLevel typeCheckLevel;

  /** Whether the Normalize pass runs before pass being tested. */
  private boolean normalizeEnabled = false;

  /** Whether the expected JS strings should be normalized. */
  private boolean normalizeExpected = false;

  /** Whether to check that all line number information is preserved. */
  private boolean checkLineNumbers = true;

  /** Whether we expect parse warnings in the current test. */
  private boolean expectParseWarningsThisTest = false;

  /**
   * An expected symbol table error. Only useful for testing the
   * symbol table error-handling.
   */
  private DiagnosticType expectedSymbolTableError = null;

  /**
   * Whether the MarkNoSideEffectsCalls pass runs before the pass being tested
   */
  private boolean markNoSideEffects = false;

  /** The most recently used Compiler instance. */
  private Compiler lastCompiler;

  /**
   * Whether to acceptES5 source.
   */
  private boolean acceptES5 = true;

  /**
   * Whether externs changes should be allowed for this pass.
   */
  private boolean allowExternsChanges = false;

  /**
   * Whether the AST should be validated.
   */
  private boolean astValidationEnabled = true;

  private String filename = "testcode";

  /**
   * Constructs a test.
   *
   * @param externs Externs JS as a string
   * @param compareAsTree True to compare output & expected as a node tree.
   *     99% of the time you want to compare as a tree. There are a few
   *     special cases where you don't, like if you want to test the code
   *     printing of "unnatural" syntax trees. For example,
   *
   * <pre>
   * IF
   *   IF
   *     STATEMENT
   * ELSE
   *   STATEMENT
   * </pre>
   */
  protected CompilerTestCase(String externs, boolean compareAsTree) {
    this.externsInputs = ImmutableList.of(
        SourceFile.fromCode("externs", externs));
    this.compareAsTree = compareAsTree;
    this.parseTypeInfo = false;
  }

  /**
   * Constructs a test. Uses AST comparison.
   * @param externs Externs JS as a string
   */
  protected CompilerTestCase(String externs) {
    this(externs, true);
  }

  /**
   * Constructs a test. Uses AST comparison and no externs.
   */
  protected CompilerTestCase() {
    this("", true);
  }

  @Override protected void tearDown() throws Exception {
    super.tearDown();
    expectParseWarningsThisTest = false;
  }

  /**
   * Gets the compiler pass instance to use for a test.
   *
   * @param compiler The compiler
   * @return The pass to test
   */
  protected abstract CompilerPass getProcessor(Compiler compiler);


  /**
   * Gets the compiler options to use for this test. Use getProcessor to
   * determine what passes should be run.
   */
  protected CompilerOptions getOptions() {
    return getOptions(new CompilerOptions());
  }

  /**
   * Gets the compiler options to use for this test. Use getProcessor to
   * determine what passes should be run.
   */
  protected CompilerOptions getOptions(CompilerOptions options) {
    if (this.acceptES5) {
      options.setLanguageIn(LanguageMode.ECMASCRIPT5);
    }

    // This doesn't affect whether checkSymbols is run--it just affects
    // whether variable warnings are filtered.
    options.checkSymbols = true;

    options.setWarningLevel(
        DiagnosticGroups.MISSING_PROPERTIES, CheckLevel.WARNING);
    options.setWarningLevel(
        DiagnosticGroups.INVALID_CASTS, CheckLevel.WARNING);
    options.setCodingConvention(getCodingConvention());
    return options;
  }

  protected CodingConvention getCodingConvention() {
    return new GoogleCodingConvention();
  }

  public void setFilename(String filename) {
    this.filename = filename;
  }

  /**
   * Returns the number of times the pass should be run before results are
   * verified.
   */
  protected int getNumRepetitions() {
    // Since most compiler passes should be idempotent, we run each pass twice
    // by default.
    return 2;
  }

  /** Expect warnings without source information. */
  void allowSourcelessWarnings() {
    allowSourcelessWarnings = true;
  }

  /** The most recently used JSComp instance. */
  Compiler getLastCompiler() {
    return lastCompiler;
  }

  /**
   * Whether to allow ECMASCRIPT5 source parsing.
   */
  protected void enableEcmaScript5(boolean acceptES5) {
    this.acceptES5 = acceptES5;
  }

  /**
   * Whether to allow externs changes.
   */
  protected void allowExternsChanges(boolean allowExternsChanges) {
    this.allowExternsChanges = allowExternsChanges;
  }

  /**
   * Perform type checking before running the test pass. This will check
   * for type errors and annotate nodes with type information.
   *
   * @param level the level of severity to report for type errors
   *
   * @see TypeCheck
   */
  public void enableTypeCheck(CheckLevel level) {
    typeCheckEnabled  = true;
    typeCheckLevel = level;
  }

  /**
   * Check to make sure that line numbers were preserved.
   */
  public void enableLineNumberCheck(boolean newVal) {
    checkLineNumbers = newVal;
  }

  /**
   * Do not run type checking before running the test pass.
   *
   * @see TypeCheck
   */
  void disableTypeCheck() {
    typeCheckEnabled  = false;
  }

  /**
   * Process closure library primitives.
   */
  // TODO(nicksantos): Fix other passes to use this when appropriate.
  void enableClosurePass() {
    closurePassEnabled = true;
  }

  /**
   * Perform AST normalization before running the test pass, and anti-normalize
   * after running it.
   *
   * @see Normalize
   */
  protected void enableNormalize() {
    enableNormalize(true);
  }

  /**
   * Perform AST normalization before running the test pass, and anti-normalize
   * after running it.
   *
   * @param normalizeExpected Whether to perform normalization on the
   * expected JS result.
   * @see Normalize
   */
  protected void enableNormalize(boolean normalizeExpected) {
    normalizeEnabled = true;
    this.normalizeExpected = normalizeExpected;
  }

  /**
   * Don't perform AST normalization before running the test pass.
   * @see Normalize
   */
  protected void disableNormalize() {
    normalizeEnabled = false;
  }

  /**
   * Run the MarkSideEffectCalls pass before running the test pass.
   *
   * @see MarkNoSideEffectCalls
   */
  void enableMarkNoSideEffects() {
    markNoSideEffects  = true;
  }

  /**
   * Whether to allow Validate the AST after each run of the pass.
   */
  protected void enableAstValidation(boolean validate) {
    astValidationEnabled = validate;
  }

  /** Whether we should ignore parse warnings for the current test method. */
  protected void setExpectParseWarningsThisTest() {
    expectParseWarningsThisTest = true;
  }

  /** Returns a newly created TypeCheck. */
  private static TypeCheck createTypeCheck(Compiler compiler,
      CheckLevel level) {
    ReverseAbstractInterpreter rai =
        new SemanticReverseAbstractInterpreter(compiler.getCodingConvention(),
            compiler.getTypeRegistry());

    return new TypeCheck(compiler, rai, compiler.getTypeRegistry(),
        level, CheckLevel.OFF);
  }

  /**
   * Verifies that the compiler pass's JS output matches the expected output.
   *
   * @param js Input
   * @param expected Expected JS output
   */
  public void test(String js, String expected) {
    test(js, expected, (DiagnosticType) null);
  }

  /**
   * Verifies that the compiler pass's JS output matches the expected output,
   * or that an expected error is encountered.
   *
   * @param js Input
   * @param expected Expected output, or null if an error is expected
   * @param error Expected error, or null if no error is expected
   */
  public void test(String js, String expected, DiagnosticType error) {
    test(js, expected, error, null);
  }


  /**
   * Verifies that the compiler pass's JS output matches the expected output,
   * or that an expected error is encountered.
   *
   * @param js Input
   * @param expected Expected output, or null if an error is expected
   * @param error Expected error, or null if no error is expected
   * @param warning Expected warning, or null if no warning is expected
   * @param description The content of the error expected
   */
  public void test(String js, String expected, DiagnosticType error,
                   DiagnosticType warning, String description) {
    test(externsInputs, js, expected, error, warning, description);
  }

  /**
   * Verifies that the compiler pass's JS output matches the expected output
   * and (optionally) that an expected warning is issued. Or, if an error is
   * expected, this method just verifies that the error is encountered.
   *
   * @param js Input
   * @param expected Expected output, or null if an error is expected
   * @param error Expected error, or null if no error is expected
   * @param warning Expected warning, or null if no warning is expected
   */
  public void test(String js, String expected,
                   DiagnosticType error, DiagnosticType warning) {
    test(externsInputs, js, expected, error, warning, null);
  }

  /**
   * Verifies that the compiler pass's JS output matches the expected output
   * and (optionally) that an expected warning is issued. Or, if an error is
   * expected, this method just verifies that the error is encountered.
   *
   * @param externs Externs input
   * @param js Input
   * @param expected Expected output, or null if an error is expected
   * @param error Expected error, or null if no error is expected
   * @param warning Expected warning, or null if no warning is expected
   */
  public void test(String externs, String js, String expected,
                   DiagnosticType error, DiagnosticType warning) {
    test(externs, js, expected, error, warning, null);
  }

  /**
   * Verifies that the compiler pass's JS output matches the expected output
   * and (optionally) that an expected warning is issued. Or, if an error is
   * expected, this method just verifies that the error is encountered.
   *
   * @param externs Externs input
   * @param js Input
   * @param expected Expected output, or null if an error is expected
   * @param error Expected error, or null if no error is expected
   * @param warning Expected warning, or null if no warning is expected
   * @param description The description of the expected warning,
   *      or null if no warning is expected or if the warning's description
   *      should not be examined
   */
  public void test(String externs, String js, String expected,
                   DiagnosticType error, DiagnosticType warning,
                   String description) {
    List<SourceFile> externsInputs = ImmutableList.of(
        SourceFile.fromCode("externs", externs));
    test(externsInputs, js, expected, error, warning, description);
  }

  /**
   * Verifies that the compiler pass's JS output matches the expected output
   * and (optionally) that an expected warning is issued. Or, if an error is
   * expected, this method just verifies that the error is encountered.
   *
   * @param externs Externs inputs
   * @param js Input
   * @param expected Expected output, or null if an error is expected
   * @param error Expected error, or null if no error is expected
   * @param warning Expected warning, or null if no warning is expected
   * @param description The description of the expected warning,
   *      or null if no warning is expected or if the warning's description
   *      should not be examined
   */
  public void test(List<SourceFile> externs, String js, String expected,
                   DiagnosticType error,
                   DiagnosticType warning, String description) {
    Compiler compiler = createCompiler();
    lastCompiler = compiler;

    CompilerOptions options = getOptions();

    if (this.acceptES5) {
      options.setLanguageIn(LanguageMode.ECMASCRIPT5);
    }
    // Note that in this context, turning on the checkTypes option won't
    // actually cause the type check to run.
    options.checkTypes = parseTypeInfo;
    compiler.init(externs, ImmutableList.of(
        SourceFile.fromCode(filename, js)), options);

    BaseJSTypeTestCase.addNativeProperties(compiler.getTypeRegistry());

    test(compiler, maybeCreateArray(expected), error, warning, description);
  }

  private String[] maybeCreateArray(String expected) {
    if (expected != null) {
      return new String[] { expected };
    }
    return null;
  }

  /**
   * Verifies that the compiler pass's JS output matches the expected output.
   *
   * @param js Inputs
   * @param expected Expected JS output
   */
  public void test(String[] js, String[] expected) {
    test(js, expected, null);
  }

  /**
   * Verifies that the compiler pass's JS output matches the expected output,
   * or that an expected error is encountered.
   *
   * @param js Inputs
   * @param expected Expected JS output
   * @param error Expected error, or null if no error is expected
   */
  public void test(String[] js, String[] expected, DiagnosticType error) {
    test(js, expected, error, null);
  }

  /**
   * Verifies that the compiler pass's JS output matches the expected output
   * and (optionally) that an expected warning is issued. Or, if an error is
   * expected, this method just verifies that the error is encountered.
   *
   * @param js Inputs
   * @param expected Expected JS output
   * @param error Expected error, or null if no error is expected
   * @param warning Expected warning, or null if no warning is expected
   */
  public void test(String[] js, String[] expected, DiagnosticType error,
                   DiagnosticType warning) {
    test(js, expected, error, warning, null);
  }

  /**
   * Verifies that the compiler pass's JS output matches the expected output
   * and (optionally) that an expected warning is issued. Or, if an error is
   * expected, this method just verifies that the error is encountered.
   *
   * @param js Inputs
   * @param expected Expected JS output
   * @param error Expected error, or null if no error is expected
   * @param warning Expected warning, or null if no warning is expected
   * @param description The description of the expected warning,
   *      or null if no warning is expected or if the warning's description
   *      should not be examined
   */
  public void test(String[] js, String[] expected, DiagnosticType error,
                   DiagnosticType warning, String description) {
    Compiler compiler = createCompiler();
    lastCompiler = compiler;

    List<SourceFile> inputs = Lists.newArrayList();
    for (int i = 0; i < js.length; i++) {
      inputs.add(SourceFile.fromCode("input" + i, js[i]));
    }
    compiler.init(externsInputs, inputs, getOptions());
    test(compiler, expected, error, warning, description);
  }

  /**
   * Verifies that the compiler pass's JS output matches the expected output.
   *
   * @param modules Module inputs
   * @param expected Expected JS outputs (one per module)
   */
  public void test(JSModule[] modules, String[] expected) {
    test(modules, expected, null);
  }

  /**
   * Verifies that the compiler pass's JS output matches the expected output,
   * or that an expected error is encountered.
   *
   * @param modules Module inputs
   * @param expected Expected JS outputs (one per module)
   * @param error Expected error, or null if no error is expected
   */
  public void test(JSModule[] modules, String[] expected,
      DiagnosticType error) {
    test(modules, expected, error, null);
  }

  /**
   * Verifies that the compiler pass's JS output matches the expected output
   * and (optionally) that an expected warning is issued. Or, if an error is
   * expected, this method just verifies that the error is encountered.
   *
   * @param modules Module inputs
   * @param expected Expected JS outputs (one per module)
   * @param error Expected error, or null if no error is expected
   * @param warning Expected warning, or null if no warning is expected
   */
  public void test(JSModule[] modules, String[] expected,
                   DiagnosticType error, DiagnosticType warning) {
    Compiler compiler = createCompiler();
    lastCompiler = compiler;

    compiler.initModules(
        externsInputs, Lists.newArrayList(modules), getOptions());
    test(compiler, expected, error, warning);
  }

  /**
   * Verifies that the compiler pass's JS output is the same as its input.
   *
   * @param js Input and output
   */
  public void testSame(String js) {
    test(js, js);
  }

  /**
   * Verifies that the compiler pass's JS output is the same as its input
   * and (optionally) that an expected warning is issued.
   *
   * @param js Input and output
   * @param warning Expected warning, or null if no warning is expected
   */
  public void testSame(String js, DiagnosticType warning) {
    test(js, js, null, warning);
  }

  /**
   * Verifies that the compiler pass's JS output is the same as its input
   * and (optionally) that an expected warning is issued.
   *
   * @param js Input and output
   * @param diag Expected error or warning, or null if none is expected
   * @param error true if diag is an error, false if it is a warning
   */
  public void testSame(String js, DiagnosticType diag, boolean error) {
    if (error) {
      test(js, js, diag);
    } else {
      test(js, js, null, diag);
    }
  }

  /**
   * Verifies that the compiler pass's JS output is the same as its input
   * and (optionally) that an expected warning is issued.
   *
   * @param externs Externs input
   * @param js Input and output
   * @param warning Expected warning, or null if no warning is expected
   */
  public void testSame(String externs, String js, DiagnosticType warning) {
    testSame(externs, js, warning, null);
  }

  /**
   * Verifies that the compiler pass's JS output is the same as its input
   * and (optionally) that an expected warning is issued.
   *
   * @param externs Externs input
   * @param js Input and output
   * @param diag Expected error or warning, or null if none is expected
   * @param error true if diag is an error, false if it is a warning
   */
  public void testSame(
      String externs, String js, DiagnosticType diag, boolean error) {
    if (error) {
      test(externs, js, js, diag, null);
    } else {
      test(externs, js, js, null, diag);
    }
  }

  /**
   * Verifies that the compiler pass's JS output is the same as its input
   * and (optionally) that an expected warning and description is issued.
   *
   * @param externs Externs input
   * @param js Input and output
   * @param warning Expected warning, or null if no warning is expected
   * @param description The description of the expected warning,
   *      or null if no warning is expected or if the warning's description
   *      should not be examined
   */
  public void testSame(String externs, String js, DiagnosticType warning,
                       String description) {
    List<SourceFile> externsInputs = ImmutableList.of(
        SourceFile.fromCode("externs", externs));
    test(externsInputs, js, js, null, warning, description);
  }

  /**
   * Verifies that the compiler pass's JS output is the same as its input.
   *
   * @param js Inputs and outputs
   */
  public void testSame(String[] js) {
    test(js, js);
  }

  /**
   * Verifies that the compiler pass's JS output is the same as its input,
   * and emits the given error.
   *
   * @param js Inputs and outputs
   * @param error Expected error, or null if no error is expected
   */
  public void testSame(String[] js, DiagnosticType error) {
    test(js, js, error);
  }

  /**
   * Verifies that the compiler pass's JS output is the same as its input,
   * and emits the given error and warning.
   *
   * @param js Inputs and outputs
   * @param error Expected error, or null if no error is expected
   * @param warning Expected warning, or null if no warning is expected
   */
  public void testSame(
      String[] js, DiagnosticType error, DiagnosticType warning) {
    test(js, js, error, warning);
  }

  /**
   * Verifies that the compiler pass's JS output is the same as the input.
   *
   * @param modules Module inputs
   */
  public void testSame(JSModule[] modules) {
    testSame(modules, null);
  }

  /**
   * Verifies that the compiler pass's JS output is the same as the input.
   *
   * @param modules Module inputs
   * @param warning A warning, or null for no expected warning.
   */
  public void testSame(JSModule[] modules, DiagnosticType warning) {
    try {
      String[] expected = new String[modules.length];
      for (int i = 0; i < modules.length; i++) {
        expected[i] = "";
        for (CompilerInput input : modules[i].getInputs()) {
          expected[i] += input.getSourceFile().getCode();
        }
      }
      test(modules, expected, null, warning);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * Verifies that the compiler pass's JS output matches the expected output
   * and (optionally) that an expected warning is issued. Or, if an error is
   * expected, this method just verifies that the error is encountered.
   *
   * @param compiler A compiler that has been initialized via
   *     {@link Compiler#init}
   * @param expected Expected output, or null if an error is expected
   * @param error Expected error, or null if no error is expected
   * @param warning Expected warning, or null if no warning is expected
   */
  protected void test(Compiler compiler, String[] expected,
                      DiagnosticType error, DiagnosticType warning) {
    test(compiler, expected, error, warning, null);
  }


  /**
   * Verifies that the compiler pass's JS output matches the expected output
   * and (optionally) that an expected warning is issued. Or, if an error is
   * expected, this method just verifies that the error is encountered.
   *
   * @param compiler A compiler that has been initialized via
   *     {@link Compiler#init}
   * @param expected Expected output, or null if an error is expected
   * @param error Expected error, or null if no error is expected
   * @param warning Expected warning, or null if no warning is expected
   * @param description The description of the expected warning,
   *      or null if no warning is expected or if the warning's description
   *      should not be examined
   */
  private void test(Compiler compiler, String[] expected,
                    DiagnosticType error, DiagnosticType warning,
                    String description) {
    CodeChangeHandler recentChange = new  CodeChangeHandler();
    compiler.addChangeHandler(recentChange);

    Node root = compiler.parseInputs();
    assertTrue("Unexpected parse error(s): " +
        Joiner.on("\n").join(compiler.getErrors()), root != null);
    if (!expectParseWarningsThisTest) {
      assertTrue("Unexpected parse warnings(s): " +
          Joiner.on("\n").join(compiler.getWarnings()),
          compiler.getWarnings().length == 0);
    }

    if (astValidationEnabled) {
      (new AstValidator()).validateRoot(root);
    }
    Node externsRoot = root.getFirstChild();
    Node mainRoot = root.getLastChild();

    // Save the tree for later comparison.
    Node rootClone = root.cloneTree();
    Node externsRootClone = rootClone.getFirstChild();
    Node mainRootClone = rootClone.getLastChild();

    int numRepetitions = getNumRepetitions();
    ErrorManager[] errorManagers = new ErrorManager[numRepetitions];
    int aggregateWarningCount = 0;
    List<JSError> aggregateWarnings = Lists.newArrayList();
    boolean hasCodeChanged = false;

    assertFalse("Code should not change before processing",
        recentChange.hasCodeChanged());

    for (int i = 0; i < numRepetitions; ++i) {
      if (compiler.getErrorCount() == 0) {
        errorManagers[i] = new BlackHoleErrorManager(compiler);

        // Only run process closure primitives once, if asked.
        if (closurePassEnabled && i == 0) {
          recentChange.reset();
          new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR)
              .process(null, mainRoot);
          hasCodeChanged = hasCodeChanged || recentChange.hasCodeChanged();
        }

        // Only run the type checking pass once, if asked.
        // Running it twice can cause unpredictable behavior because duplicate
        // objects for the same type are created, and the type system
        // uses reference equality to compare many types.
        if (typeCheckEnabled && i == 0) {
          TypeCheck check = createTypeCheck(compiler, typeCheckLevel);
          check.processForTesting(externsRoot, mainRoot);
        }

        // Only run the normalize pass once, if asked.
        if (normalizeEnabled && i == 0) {
          normalizeActualCode(compiler, externsRoot, mainRoot);
        }

        if (markNoSideEffects && i == 0) {
          MarkNoSideEffectCalls mark = new MarkNoSideEffectCalls(compiler);
          mark.process(externsRoot, mainRoot);
        }

        recentChange.reset();

        getProcessor(compiler).process(externsRoot, mainRoot);
        if (astValidationEnabled) {
          (new AstValidator()).validateRoot(root);
        }
        if (checkLineNumbers) {
          (new LineNumberCheck(compiler)).process(externsRoot, mainRoot);
        }

        hasCodeChanged = hasCodeChanged || recentChange.hasCodeChanged();
        aggregateWarningCount += errorManagers[i].getWarningCount();
        aggregateWarnings.addAll(Lists.newArrayList(compiler.getWarnings()));

        if (normalizeEnabled) {
          boolean verifyDeclaredConstants = true;
          new Normalize.VerifyConstants(compiler, verifyDeclaredConstants)
              .process(externsRoot, mainRoot);
        }
      }
    }

    if (error == null) {
      assertEquals(
          "Unexpected error(s): " + Joiner.on("\n").join(compiler.getErrors()),
          0, compiler.getErrorCount());

      // Verify the symbol table.
      ErrorManager symbolTableErrorManager =
          new BlackHoleErrorManager(compiler);
      Node expectedRoot = null;
      if (expected != null) {
        expectedRoot = parseExpectedJs(expected);
        expectedRoot.detachFromParent();
      }

      JSError[] stErrors = symbolTableErrorManager.getErrors();
      if (expectedSymbolTableError != null) {
        assertEquals("There should be one error.", 1, stErrors.length);
        assertEquals(expectedSymbolTableError, stErrors[0].getType());
      } else {
        assertEquals("Unexpected symbol table error(s): " +
            Joiner.on("\n").join(stErrors),
            0, stErrors.length);
      }

      if (warning == null) {
        assertEquals(
            "Unexpected warning(s): " + Joiner.on("\n").join(aggregateWarnings),
            0, aggregateWarningCount);
      } else {
        assertEquals("There should be one warning, repeated " + numRepetitions +
            " time(s).", numRepetitions, aggregateWarningCount);
        for (int i = 0; i < numRepetitions; ++i) {
          JSError[] warnings = errorManagers[i].getWarnings();
          JSError actual = warnings[0];
          assertEquals(warning, actual.getType());

          // Make sure that source information is always provided.
          if (!allowSourcelessWarnings) {
            assertTrue("Missing source file name in warning",
                actual.sourceName != null && !actual.sourceName.isEmpty());
            assertTrue("Missing line number in warning",
                -1 != actual.lineNumber);
            assertTrue("Missing char number in warning",
                -1 != actual.getCharno());
          }

          if (description != null) {
            assertEquals(description, actual.description);
          }
        }
      }

      // If we ran normalize on the AST, we must also run normalize on the
      // clone before checking for changes.
      if (normalizeEnabled) {
        normalizeActualCode(compiler, externsRootClone, mainRootClone);
      }

      boolean codeChange = !mainRootClone.isEquivalentTo(mainRoot);
      boolean externsChange = !externsRootClone.isEquivalentTo(externsRoot);

      // Generally, externs should not be change by the compiler passes.
      if (externsChange && !allowExternsChanges) {
        String explanation = externsRootClone.checkTreeEquals(externsRoot);
        fail("Unexpected changes to externs" +
            "\nExpected: " + compiler.toSource(externsRootClone) +
            "\nResult: " + compiler.toSource(externsRoot) +
            "\n" + explanation);
      }

      if (!codeChange && !externsChange) {
        assertFalse(
            "compiler.reportCodeChange() was called " +
            "even though nothing changed",
            hasCodeChanged);
      } else {
        assertTrue("compiler.reportCodeChange() should have been called",
            hasCodeChanged);
      }

      if (expected != null) {
        if (compareAsTree) {
          String explanation = expectedRoot.checkTreeEquals(mainRoot);
          assertNull("\nExpected: " + compiler.toSource(expectedRoot) +
              "\nResult: " + compiler.toSource(mainRoot) +
              "\n" + explanation, explanation);
        } else if (expected != null) {
          assertEquals(
              Joiner.on("").join(expected), compiler.toSource(mainRoot));
        }
      }

      // Verify normalization is not invalidated.
      Node normalizeCheckRootClone = root.cloneTree();
      Node normalizeCheckExternsRootClone = normalizeCheckRootClone.getFirstChild();
      Node normalizeCheckMainRootClone = normalizeCheckRootClone.getLastChild();
      new PrepareAst(compiler).process(
          normalizeCheckExternsRootClone, normalizeCheckMainRootClone);
      String explanation =
          normalizeCheckMainRootClone.checkTreeEquals(mainRoot);
      assertNull("Node structure normalization invalidated.\nExpected: " +
          compiler.toSource(normalizeCheckMainRootClone) +
          "\nResult: " + compiler.toSource(mainRoot) +
          "\n" + explanation, explanation);

      // TODO(johnlenz): enable this for most test cases.
      // Currently, this invalidates test for while-loops, for-loop
      // initializers, and other naming.  However, a set of code
      // (Closure primitive rewrites, etc) runs before the Normalize pass,
      // so this can't be force on everywhere.
      if (normalizeEnabled) {
        new Normalize(compiler, true).process(
            normalizeCheckExternsRootClone, normalizeCheckMainRootClone);
        explanation =  normalizeCheckMainRootClone.checkTreeEquals(mainRoot);
        assertNull("Normalization invalidated.\nExpected: " +
            compiler.toSource(normalizeCheckMainRootClone) +
            "\nResult: " + compiler.toSource(mainRoot) +
            "\n" + explanation, explanation);
      }
    } else {
      String errors = "";
      for (JSError actualError : compiler.getErrors()) {
        errors += actualError.description + "\n";
      }
      assertEquals("There should be one error. " + errors,
          1, compiler.getErrorCount());
      assertEquals(errors, error, compiler.getErrors()[0].getType());

      if (warning != null) {
        String warnings = "";
        for (JSError actualError : compiler.getWarnings()) {
          warnings += actualError.description + "\n";
        }
        assertEquals("There should be one warning. " + warnings,
            1, compiler.getWarningCount());
        assertEquals(warnings, warning, compiler.getWarnings()[0].getType());
      }
    }
  }

  private void normalizeActualCode(
      Compiler compiler, Node externsRoot, Node mainRoot) {
    Normalize normalize = new Normalize(compiler, false);
    normalize.process(externsRoot, mainRoot);
  }

  /**
   * Parses expected JS inputs and returns the root of the parse tree.
   */
  protected Node parseExpectedJs(String[] expected) {
    Compiler compiler = createCompiler();
    List<SourceFile> inputs = Lists.newArrayList();
    for (int i = 0; i < expected.length; i++) {
      inputs.add(SourceFile.fromCode("expected" + i, expected[i]));
    }
    compiler.init(externsInputs, inputs, getOptions());
    Node root = compiler.parseInputs();
    assertTrue("Unexpected parse error(s): " +
        Joiner.on("\n").join(compiler.getErrors()), root != null);
    Node externsRoot = root.getFirstChild();
    Node mainRoot = externsRoot.getNext();
    // Only run the normalize pass, if asked.
    if (normalizeEnabled && normalizeExpected && !compiler.hasErrors()) {
      Normalize normalize = new Normalize(compiler, false);
      normalize.process(externsRoot, mainRoot);
    }
    return mainRoot;
  }

  protected Node parseExpectedJs(String expected) {
    return parseExpectedJs(new String[] {expected});
  }

  /**
   * Generates a list of modules from a list of inputs, such that each module
   * depends on the module before it.
   */
  static JSModule[] createModuleChain(String... inputs) {
    JSModule[] modules = createModules(inputs);
    for (int i = 1; i < modules.length; i++) {
      modules[i].addDependency(modules[i - 1]);
    }
    return modules;
  }

  /**
   * Generates a list of modules from a list of inputs, such that each module
   * depends on the first module.
   */
  static JSModule[] createModuleStar(String... inputs) {
    JSModule[] modules = createModules(inputs);
    for (int i = 1; i < modules.length; i++) {
      modules[i].addDependency(modules[0]);
    }
    return modules;
  }

  /**
   * Generates a list of modules from a list of inputs, such that modules
   * form a bush formation. In a bush formation, module 2 depends
   * on module 1, and all other modules depend on module 2.
   */
  static JSModule[] createModuleBush(String ... inputs) {
    Preconditions.checkState(inputs.length > 2);
    JSModule[] modules = createModules(inputs);
    for (int i = 1; i < modules.length; i++) {
      modules[i].addDependency(modules[i == 1 ? 0 : 1]);
    }
    return modules;
  }

  /**
   * Generates a list of modules from a list of inputs, such that modules
   * form a tree formation. In a tree formation, module N depends on
   * module `floor(N/2)`, So the modules form a balanced binary tree.
   */
  static JSModule[] createModuleTree(String ... inputs) {
    JSModule[] modules = createModules(inputs);
    for (int i = 1; i < modules.length; i++) {
      modules[i].addDependency(modules[(i - 1) / 2]);
    }
    return modules;
  }

  /**
   * Generates a list of modules from a list of inputs. Does not generate any
   * dependencies between the modules.
   */
  static JSModule[] createModules(String... inputs) {
    JSModule[] modules = new JSModule[inputs.length];
    for (int i = 0; i < inputs.length; i++) {
      JSModule module = modules[i] = new JSModule("m" + i);
      module.add(SourceFile.fromCode("i" + i, inputs[i]));
    }
    return modules;
  }

  private static class BlackHoleErrorManager extends BasicErrorManager {
    private BlackHoleErrorManager(Compiler compiler) {
      compiler.setErrorManager(this);
    }

    @Override
    public void println(CheckLevel level, JSError error) {}

    @Override
    public void printSummary() {}
  }

  Compiler createCompiler() {
    Compiler compiler = new Compiler();
    return compiler;
  }

  protected void setExpectedSymbolTableError(DiagnosticType type) {
    this.expectedSymbolTableError = type;
  }

  /** Finds the first matching qualified name node in post-traversal order. */
  protected final Node findQualifiedNameNode(final String name, Node root) {
    final List<Node> matches = Lists.newArrayList();
    NodeUtil.visitPostOrder(root,
        new NodeUtil.Visitor() {
          @Override public void visit(Node n) {
            if (name.equals(n.getQualifiedName())) {
              matches.add(n);
            }
          }
        },
        Predicates.<Node>alwaysTrue());
    return matches.get(0);
  }
}