-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
CompilerTest.java
2585 lines (2196 loc) · 96.3 KB
/
CompilerTest.java
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
/*
* Copyright 2010 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 static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.javascript.jscomp.CompilerTestCase.lines;
import static com.google.javascript.jscomp.testing.JSCompCorrespondences.DIAGNOSTIC_EQUALITY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.fail;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.io.Files;
import com.google.debugging.sourcemap.FilePosition;
import com.google.debugging.sourcemap.SourceMapConsumerV3;
import com.google.debugging.sourcemap.SourceMapGeneratorV3;
import com.google.debugging.sourcemap.proto.Mapping.OriginalMapping;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import com.google.javascript.jscomp.deps.ModuleLoader.ResolutionMode;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.InputId;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.StaticSourceFile.SourceKind;
import com.google.javascript.rhino.Token;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** @author johnlenz@google.com (John Lenz) */
@RunWith(JUnit4.class)
public final class CompilerTest {
// Verify the line and column information is maintained after a reset
@Test
public void testCodeBuilderColumnAfterReset() {
Compiler.CodeBuilder cb = new Compiler.CodeBuilder();
String js = "foo();\ngoo();";
cb.append(js);
assertThat(cb.toString()).isEqualTo(js);
assertThat(cb.getLineIndex()).isEqualTo(1);
assertThat(cb.getColumnIndex()).isEqualTo(6);
cb.reset();
assertThat(cb.toString()).isEmpty();
assertThat(cb.getLineIndex()).isEqualTo(1);
assertThat(cb.getColumnIndex()).isEqualTo(6);
}
@Test
public void testCodeBuilderAppend() {
Compiler.CodeBuilder cb = new Compiler.CodeBuilder();
cb.append("foo();");
assertThat(cb.getLineIndex()).isEqualTo(0);
assertThat(cb.getColumnIndex()).isEqualTo(6);
cb.append("goo();");
assertThat(cb.getLineIndex()).isEqualTo(0);
assertThat(cb.getColumnIndex()).isEqualTo(12);
// newline reset the column index
cb.append("blah();\ngoo();");
assertThat(cb.getLineIndex()).isEqualTo(1);
assertThat(cb.getColumnIndex()).isEqualTo(6);
}
@Test
public void testCyclicalDependencyInInputs() {
List<SourceFile> inputs = ImmutableList.of(
SourceFile.fromCode(
"gin", "goog.provide('gin'); goog.require('tonic'); var gin = {};"),
SourceFile.fromCode("tonic",
"goog.provide('tonic'); goog.require('gin'); var tonic = {};"),
SourceFile.fromCode(
"mix", "goog.require('gin'); goog.require('tonic');"));
CompilerOptions options = new CompilerOptions();
options.setIdeMode(true);
options.setDependencyOptions(DependencyOptions.pruneLegacyForEntryPoints(ImmutableList.of()));
Compiler compiler = new Compiler();
compiler.init(ImmutableList.<SourceFile>of(), inputs, options);
compiler.parseInputs();
assertThat(compiler.jsRoot.getParent()).isEqualTo(compiler.externAndJsRoot);
assertThat(compiler.externsRoot.getParent()).isEqualTo(compiler.externAndJsRoot);
assertThat(compiler.externAndJsRoot).isNotNull();
Node jsRoot = compiler.jsRoot;
assertThat(jsRoot.getChildCount()).isEqualTo(3);
}
@Test
public void testPrintExterns() {
List<SourceFile> externs =
ImmutableList.of(SourceFile.fromCode("extern", "/** @externs */ function alert(x) {}"));
CompilerOptions options = new CompilerOptions();
options.setPreserveTypeAnnotations(true);
options.setLanguageIn(LanguageMode.ECMASCRIPT3);
options.setPrintExterns(true);
Compiler compiler = new Compiler();
compiler.init(externs, ImmutableList.<SourceFile>of(), options);
compiler.parseInputs();
assertThat(compiler.toSource()).isEqualTo("/** @externs */ function alert(x){};");
}
@Test
public void testLocalUndefined() {
// Some JavaScript libraries like to create a local instance of "undefined",
// to ensure that other libraries don't try to overwrite it.
//
// Most of the time, this is OK, because normalization will rename
// that variable to undefined$$1. But this won't happen if they don't
// include the default externs.
//
// This test is just to make sure that the compiler doesn't crash.
CompilerOptions options = new CompilerOptions();
CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options);
Compiler compiler = new Compiler();
SourceFile externs = SourceFile.fromCode("externs.js", "");
SourceFile input = SourceFile.fromCode("input.js",
"(function (undefined) { alert(undefined); })();");
compiler.compile(externs, input, options);
}
private static String normalize(String path) {
return path.replace(File.separator, "/");
}
@Test
public void testInputSourceMaps() throws Exception {
FilePosition originalSourcePosition = new FilePosition(17, 25);
ImmutableMap<String, SourceMapInput> inputSourceMaps = ImmutableMap.of(
normalize("generated_js/example.js"),
sourcemap(
normalize("generated_js/example.srcmap"),
normalize("../original/source.html"),
originalSourcePosition));
String origSourceName = normalize("original/source.html");
List<SourceFile> originalSources = ImmutableList.of(
SourceFile.fromCode(origSourceName, "<div ng-show='foo()'>"));
CompilerOptions options = new CompilerOptions();
options.inputSourceMaps = inputSourceMaps;
Compiler compiler = new Compiler();
compiler.init(new ArrayList<SourceFile>(), originalSources, options);
assertThat(compiler.getSourceMapping(normalize("generated_js/example.js"), 3, 3))
.isEqualTo(
OriginalMapping.newBuilder()
.setOriginalFile(origSourceName)
.setLineNumber(18)
.setColumnPosition(25)
.setIdentifier("testSymbolName")
.build());
assertThat(compiler.getSourceLine(origSourceName, 1)).isEqualTo("<div ng-show='foo()'>");
}
private SourceMapInput sourcemap(String sourceMapPath, String originalSource,
FilePosition originalSourcePosition) throws Exception {
SourceMapGeneratorV3 sourceMap = new SourceMapGeneratorV3();
sourceMap.addMapping(originalSource, "testSymbolName", originalSourcePosition,
new FilePosition(1, 1), new FilePosition(100, 1));
StringBuilder output = new StringBuilder();
sourceMap.appendTo(output, "unused.js");
return new SourceMapInput(SourceFile.fromCode(sourceMapPath, output.toString()));
}
private static final String SOURCE_MAP_TEST_CODE =
Joiner.on("\n")
.join(
"var X = (function () {",
" function X(input) {",
" this.y = input;",
" }",
" return X;",
"}());",
"console.log(new X(1));");
private static final String SOURCE_MAP =
"{\"version\":3,\"file\":\"foo.js\",\"sourceRoot\":\"\",\"sources\":[\"foo.ts\"],\"names\":[],\"mappings\":\"AAAA;IAGE,WAAY,KAAa;QACvB,IAAI,CAAC,CAAC,GAAG,KAAK,CAAC;IACjB,CAAC;IACH,QAAC;AAAD,CAAC,AAND,IAMC;AAED,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC\"}";
private static final String BASE64_ENCODED_SOURCE_MAP =
"data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9vLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiZm9vLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0lBR0UsV0FBWSxLQUFhO1FBQ3ZCLElBQUksQ0FBQyxDQUFDLEdBQUcsS0FBSyxDQUFDO0lBQ2pCLENBQUM7SUFDSCxRQUFDO0FBQUQsQ0FBQyxBQU5ELElBTUM7QUFFRCxPQUFPLENBQUMsR0FBRyxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMifQ==";
@Test
public void testInputSourceMapInline() {
Compiler compiler = new Compiler();
compiler.initCompilerOptionsIfTesting();
String code = SOURCE_MAP_TEST_CODE + "\n//# sourceMappingURL=" + BASE64_ENCODED_SOURCE_MAP;
CompilerInput input = new CompilerInput(SourceFile.fromCode("tmp", code));
input.getAstRoot(compiler);
SourceMapInput inputSourceMap = compiler.inputSourceMaps.get("tmp");
SourceMapConsumerV3 sourceMap = inputSourceMap.getSourceMap(null);
assertThat(sourceMap.getOriginalSources()).containsExactly("foo.ts");
assertThat(sourceMap.getOriginalSourcesContent()).isNull();
}
private static final String SOURCE_MAP_TEST_CONTENT =
Joiner.on("\n")
.join(
"var A = (function () {",
" function A(input) {",
" this.a = input;",
" }",
" return A;",
"}());",
"console.log(new A(1));");
// Similar to BASE64_ENCODED_SOURCE_MAP; contains encoded SOURCE_MAP but with
// SOURCE_MAP_TEST_CONTENT as the only item of sourcesContent corresponding
// to "../test/foo.ts" sources item.
private static final String BASE64_ENCODED_SOURCE_MAP_WITH_CONTENT =
"data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9vLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vdGVzdC9mb28udHMiXSwic291cmNlc0NvbnRlbnQiOlsidmFyIEEgPSAoZnVuY3Rpb24gKCkge1xuICAgIGZ1bmN0aW9uIEEoaW5wdXQpIHtcbiAgICAgICAgdGhpcy5hID0gaW5wdXQ7XG4gICAgfVxuICAgIHJldHVybiBBO1xufSgpKTtcbmNvbnNvbGUubG9nKG5ldyBBKDEpKTsiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7SUFHRSxXQUFZLEtBQWE7UUFDdkIsSUFBSSxDQUFDLENBQUMsR0FBRyxLQUFLLENBQUM7SUFDakIsQ0FBQztJQUNILFFBQUM7QUFBRCxDQUFDLEFBTkQsSUFNQztBQUVELE9BQU8sQ0FBQyxHQUFHLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyJ9";
@Test
public void testInputSourceMapInlineContent() {
Compiler compiler = new Compiler();
compiler.initCompilerOptionsIfTesting();
String code =
SOURCE_MAP_TEST_CODE + "\n//# sourceMappingURL=" + BASE64_ENCODED_SOURCE_MAP_WITH_CONTENT;
CompilerInput input = new CompilerInput(SourceFile.fromCode("tmp", code));
input.getAstRoot(compiler);
SourceMapInput inputSourceMap = compiler.inputSourceMaps.get("tmp");
SourceMapConsumerV3 sourceMap = inputSourceMap.getSourceMap(null);
assertThat(sourceMap.getOriginalSources()).containsExactly("../test/foo.ts");
assertThat(sourceMap.getOriginalSourcesContent()).containsExactly(SOURCE_MAP_TEST_CONTENT);
}
@Test
public void testResolveRelativeSourceMap() throws Exception {
Compiler compiler = new Compiler();
compiler.initCompilerOptionsIfTesting();
File tempDir = Files.createTempDir();
String code = SOURCE_MAP_TEST_CODE + "\n//# sourceMappingURL=foo.js.map";
File jsFile = new File(tempDir, "foo.js");
Files.asCharSink(jsFile, UTF_8).write(code);
File sourceMapFile = new File(tempDir, "foo.js.map");
Files.asCharSink(sourceMapFile, UTF_8).write(SOURCE_MAP);
CompilerInput input = new CompilerInput(SourceFile.fromFile(jsFile.getAbsolutePath()));
input.getAstRoot(compiler);
// The source map is still
assertThat(compiler.inputSourceMaps).hasSize(1);
for (SourceMapInput inputSourceMap : compiler.inputSourceMaps.values()) {
SourceMapConsumerV3 sourceMap = inputSourceMap.getSourceMap(null);
assertThat(sourceMap.getOriginalSources()).containsExactly("foo.ts");
}
}
// Make sure that the sourcemap resolution can find a sourcemap in a relative directory.
@Test
public void testResolveRelativeDirSourceMap() throws Exception {
Compiler compiler = new Compiler();
compiler.initCompilerOptionsIfTesting();
File tempDir = Files.createTempDir();
File relativedir = new File(tempDir, "/relativedir");
relativedir.mkdir();
String code = SOURCE_MAP_TEST_CODE + "\n//# sourceMappingURL=relativedir/foo.js.map";
File jsFile = new File(tempDir, "foo.js");
Files.asCharSink(jsFile, UTF_8).write(code);
File sourceMapFile = new File(relativedir, "foo.js.map");
Files.asCharSink(sourceMapFile, UTF_8).write(SOURCE_MAP);
CompilerInput input = new CompilerInput(SourceFile.fromFile(jsFile.getAbsolutePath()));
input.getAstRoot(compiler);
// The source map is still
assertThat(compiler.inputSourceMaps).hasSize(1);
for (SourceMapInput inputSourceMap : compiler.inputSourceMaps.values()) {
SourceMapConsumerV3 sourceMap = inputSourceMap.getSourceMap(null);
assertThat(sourceMap.getOriginalSources()).containsExactly("foo.ts");
}
}
@Test
public void testMissingSourceMapFile() throws Exception {
Compiler compiler = new Compiler();
compiler.initCompilerOptionsIfTesting();
File tempDir = Files.createTempDir();
String code = SOURCE_MAP_TEST_CODE + "\n//# sourceMappingURL=foo-does-not-exist.js.map";
File jsFile = new File(tempDir, "foo2.js");
Files.asCharSink(jsFile, UTF_8).write(code);
CompilerInput input = new CompilerInput(SourceFile.fromFile(jsFile.getAbsolutePath()));
input.getAstRoot(compiler);
assertThat(compiler.inputSourceMaps).hasSize(1);
TestErrorManager errorManager = new TestErrorManager();
for (SourceMapInput inputSourceMap : compiler.inputSourceMaps.values()) {
SourceMapConsumerV3 sourceMap = inputSourceMap.getSourceMap(errorManager);
assertThat(sourceMap).isNull();
}
// WARNING: Failed to resolve input sourcemap: foo-does-not-exist.js.map
assertThat(errorManager.getWarningCount()).isEqualTo(1);
}
@Test
public void testNoWarningMissingAbsoluteSourceMap() throws Exception {
TestErrorManager errorManager = new TestErrorManager();
Compiler compiler = new Compiler(errorManager);
compiler.initCompilerOptionsIfTesting();
File tempDir = Files.createTempDir();
String code = SOURCE_MAP_TEST_CODE + "\n//# sourceMappingURL=/some/missing/path/foo.js.map";
File jsFile = new File(tempDir, "foo.js");
Files.asCharSink(jsFile, UTF_8).write(code);
CompilerInput input = new CompilerInput(SourceFile.fromFile(jsFile.getAbsolutePath()));
input.getAstRoot(compiler);
// The source map is still
assertThat(compiler.inputSourceMaps).isEmpty();
// No warnings for unresolved absolute paths.
assertThat(errorManager.getWarningCount()).isEqualTo(0);
}
@Test
public void testApplyInputSourceMaps() throws Exception {
FilePosition originalSourcePosition = new FilePosition(17, 25);
ImmutableMap<String, SourceMapInput> inputSourceMaps = ImmutableMap.of(
"input.js",
sourcemap(
"input.js.map",
"input.ts",
originalSourcePosition));
CompilerOptions options = new CompilerOptions();
options.setLanguageIn(LanguageMode.ECMASCRIPT3);
options.sourceMapOutputPath = "fake/source_map_path.js.map";
options.inputSourceMaps = inputSourceMaps;
options.applyInputSourceMaps = true;
Compiler compiler = new Compiler();
compiler.compile(EMPTY_EXTERNS.get(0),
SourceFile.fromCode("input.js", "// Unmapped line\nvar x = 1;\nalert(x);"), options);
assertThat(compiler.toSource()).isEqualTo("var x=1;alert(x);");
SourceMap sourceMap = compiler.getSourceMap();
StringWriter out = new StringWriter();
sourceMap.appendTo(out, "source.js.map");
SourceMapConsumerV3 consumer = new SourceMapConsumerV3();
consumer.parse(out.toString());
// Column 5 contains the first actually mapped code ('x').
OriginalMapping mapping = consumer.getMappingForLine(1, 5);
assertThat(mapping.getOriginalFile()).isEqualTo("input.ts");
// FilePosition above is 0-based, whereas OriginalMapping is 1-based, thus 18 & 26.
assertThat(mapping.getLineNumber()).isEqualTo(18);
assertThat(mapping.getColumnPosition()).isEqualTo(26);
assertThat(mapping.getIdentifier()).isEqualTo("testSymbolName");
assertThat(consumer.getOriginalSources()).containsExactly("input.js", "input.ts");
assertThat(consumer.getOriginalSourcesContent()).isNull();
}
@Test
public void testKeepInputSourceMapsSourcesContent() throws Exception {
CompilerOptions options = new CompilerOptions();
options.setLanguageIn(LanguageMode.ECMASCRIPT3);
options.sourceMapOutputPath = "fake/source_map_path.js.map";
options.applyInputSourceMaps = true;
options.sourceMapIncludeSourcesContent = true;
String code = SOURCE_MAP_TEST_CODE + "\n//# sourceMappingURL="
+ BASE64_ENCODED_SOURCE_MAP_WITH_CONTENT;
Compiler compiler = new Compiler();
SourceFile sourceFile = SourceFile.fromCode("temp/path/input.js", code);
compiler.compile(EMPTY_EXTERNS.get(0), sourceFile, options);
assertThat(compiler.toSource()).isEqualTo(
"var X=function(){function X(input){this.y=input}return X}();console.log(new X(1));");
SourceMap sourceMap = compiler.getSourceMap();
StringWriter out = new StringWriter();
sourceMap.appendTo(out, "source.js.map");
SourceMapConsumerV3 consumer = new SourceMapConsumerV3();
consumer.parse(out.toString());
assertThat(consumer.getOriginalSources()).containsExactly("temp/test/foo.ts");
assertThat(consumer.getOriginalSourcesContent()).containsExactly(SOURCE_MAP_TEST_CONTENT);
}
@Test
public void testNoSourceMapIsGeneratedWithoutPath() {
CompilerOptions options = new CompilerOptions();
options.setLanguageIn(LanguageMode.ECMASCRIPT3);
options.applyInputSourceMaps = true;
options.sourceMapIncludeSourcesContent = true;
String code = SOURCE_MAP_TEST_CODE + "\n//# sourceMappingURL="
+ BASE64_ENCODED_SOURCE_MAP_WITH_CONTENT;
Compiler compiler = new Compiler();
SourceFile sourceFile = SourceFile.fromCode("input.js", code);
compiler.compile(EMPTY_EXTERNS.get(0), sourceFile, options);
assertThat(compiler.getSourceMap()).isNull();
}
private static final ImmutableList<SourceFile> EMPTY_EXTERNS =
ImmutableList.of(SourceFile.fromCode("externs", ""));
/**
* Ensure that the printInputDelimiter option adds a "// Input #" comment at the start of each
* "script" in the compiled output.
*/
@Test
public void testInputDelimiters() {
Compiler compiler = new Compiler();
CompilerOptions options = createNewFlagBasedOptions();
options.setPrintInputDelimiter(true);
String fileOverview = "/** @fileoverview Foo */";
List<SourceFile> inputs = ImmutableList.of(
SourceFile.fromCode("i1", ""),
SourceFile.fromCode("i2", fileOverview));
Result result = compiler.compile(EMPTY_EXTERNS, inputs, options);
assertThat(result.success).isTrue();
String outputSource = compiler.toSource();
System.err.println("Output:\n[" + outputSource + "]");
assertThat(outputSource).isEqualTo("// Input 0\n// Input 1\n");
}
/** Make sure that non-standard JSDoc annotation is not a hard error unless it is specified. */
@Test
public void testBug2176967Default() {
final String badJsDoc = "/** @XYZ */\n var x";
Compiler compiler = new Compiler();
CompilerOptions options = createNewFlagBasedOptions();
// Default is warning.
compiler.compile(SourceFile.fromCode("extern.js", ""),
SourceFile.fromCode("test.js", badJsDoc), options);
assertThat(compiler.getWarnings()).hasSize(1);
assertThat(compiler.getErrors()).isEmpty();
}
/**
* Make sure that non-standard JSDoc annotation is not a hard error nor warning when it is off.
*/
@Test
public void testBug2176967Off() {
final String badJsDoc = "/** @XYZ */\n var x";
Compiler compiler = new Compiler();
CompilerOptions options = createNewFlagBasedOptions();
options.setWarningLevel(
DiagnosticGroups.NON_STANDARD_JSDOC, CheckLevel.OFF);
compiler.compile(SourceFile.fromCode("extern.js", ""),
SourceFile.fromCode("test.js", badJsDoc), options);
assertThat(compiler.getWarnings()).isEmpty();
assertThat(compiler.getErrors()).isEmpty();
}
/**
* Make sure the non-standard JSDoc diagnostic group gives out an error when it is set to check
* level error.
*/
@Test
public void testBug2176967Error() {
final String badJsDoc = "/** @XYZ */\n var x";
Compiler compiler = new Compiler();
CompilerOptions options = createNewFlagBasedOptions();
options.setWarningLevel(
DiagnosticGroups.NON_STANDARD_JSDOC, CheckLevel.ERROR);
compiler.compile(SourceFile.fromCode("extern.js", ""),
SourceFile.fromCode("test.js", badJsDoc), options);
assertThat(compiler.getWarnings()).isEmpty();
assertThat(compiler.getErrors()).hasSize(1);
}
@Test
public void testNormalInputs() {
CompilerOptions options = new CompilerOptions();
Compiler compiler = new Compiler();
List<SourceFile> inputs = ImmutableList.of(
SourceFile.fromCode("in1", ""),
SourceFile.fromCode("in2", ""));
compiler.compile(EMPTY_EXTERNS, inputs, options);
assertThat(compiler.getInput(new InputId("externs")).isExtern()).isTrue();
assertThat(compiler.getInput(new InputId("in1")).isExtern()).isFalse();
assertThat(compiler.getInput(new InputId("in2")).isExtern()).isFalse();
}
@Test
public void testRebuildInputsFromModule() {
List<JSModule> modules = ImmutableList.of(
new JSModule("m1"), new JSModule("m2"));
modules.get(0).add(SourceFile.fromCode("in1", ""));
modules.get(1).add(SourceFile.fromCode("in2", ""));
Compiler compiler = new Compiler();
compiler.initModules(
ImmutableList.<SourceFile>of(), modules, new CompilerOptions());
modules.get(1).add(SourceFile.fromCode("in3", ""));
assertThat(compiler.getInput(new InputId("in3"))).isNull();
compiler.rebuildInputsFromModules();
assertThat(compiler.getInput(new InputId("in3"))).isNotNull();
}
@Test
public void testMalformedFunctionInExterns() {
// Just verify that no exceptions are thrown (see bug 910619).
new Compiler().compile(
ImmutableList.of(SourceFile.fromCode("externs", "function f {}")),
ImmutableList.of(SourceFile.fromCode("foo", "")),
new CompilerOptions());
}
@Test
public void testGetSourceInfoInExterns() {
// Just verify that no exceptions are thrown (see bug 910619).
Compiler compiler = new Compiler();
compiler.compile(
ImmutableList.of(SourceFile.fromCode("externs", "function f() {}\n")),
ImmutableList.of(SourceFile.fromCode("foo", "function g() {}\n")),
new CompilerOptions());
assertThat(compiler.getSourceLine("externs", 1)).isEqualTo("function f() {}");
assertThat(compiler.getSourceLine("foo", 1)).isEqualTo("function g() {}");
assertThat(compiler.getSourceLine("bar", 1)).isNull();
}
@Test
public void testFileoverviewTwice() {
List<SourceFile> input = ImmutableList.of(
SourceFile.fromCode("foo",
"/** @fileoverview */ var x; /** @fileoverview */ var y;"));
assertThat(new Compiler().compile(EMPTY_EXTERNS, input, new CompilerOptions()).success)
.isTrue();
}
// Make sure we correctly output license text.
@Test
public void testImportantCommentOutput() {
test(
"/*! Your favorite license goes here */ var x;",
"/*\n Your favorite license goes here */\n",
null);
}
// Make sure we output license text even if followed by @fileoverview.
@Test
public void testImportantCommentAndOverviewDirectiveWarning() {
List<SourceFile> input =
ImmutableList.of(
SourceFile.fromCode(
"foo",
("/*! Your favorite license goes here */\n"
+ "/** \n"
+ " * @fileoverview This is my favorite file! */\n"
+ "var x;")));
assertThat(new Compiler().compile(EMPTY_EXTERNS, input, new CompilerOptions()).success)
.isTrue();
}
// Text for the opposite order - @fileoverview, then @license.
@Test
public void testOverviewAndImportantCommentOutput() {
test(
"/** @fileoverview This is my favorite file! */\n"
+ "/*! Your favorite license goes here */\n"
+ "var x;",
"/*\n Your favorite license goes here */\n",
null);
}
// Test for sequence of @license and @fileoverview, and make sure
// all the licenses get copied over.
@Test
public void testImportantCommentOverviewImportantComment() {
test(
"/*! Another license */\n"
+ "/** @fileoverview This is my favorite file! */\n"
+ "/*! Your favorite license goes here */\n"
+ "var x;",
"/*\n Another license Your favorite license goes here */\n",
null);
}
// Make sure things work even with @license and @fileoverview in the
// same comment.
@Test
public void testCombinedImportantCommentOverviewDirectiveOutput() {
test(
"/*! Your favorite license goes here\n"
+ " * @fileoverview This is my favorite file! */\n"
+ "var x;",
"/*\n Your favorite license goes here\n" + " @fileoverview This is my favorite file! */\n",
null);
}
// Does the presence of @author change anything with the license?
@Test
public void testCombinedImportantCommentAuthorDirectiveOutput() {
test(
"/*! Your favorite license goes here\n" + " * @author Robert */\n" + "var x;",
"/*\n Your favorite license goes here\n @author Robert */\n",
null);
}
// Make sure we concatenate licenses the same way.
@Test
public void testMultipleImportantCommentDirectiveOutput() {
test(
"/*! Your favorite license goes here */\n" + "/*! Another license */\n" + "var x;",
"/*\n Your favorite license goes here Another license */\n",
null);
}
@Test
public void testImportantCommentLicenseDirectiveOutput() {
test(
"/*! Your favorite license goes here */\n" + "/** @license Another license */\n" + "var x;",
"/*\n Another license Your favorite license goes here */\n",
null);
}
@Test
public void testLicenseImportantCommentDirectiveOutput() {
test(
"/** @license Your favorite license goes here */\n" + "/*! Another license */\n" + "var x;",
"/*\n Your favorite license goes here Another license */\n",
null);
}
// Do we correctly handle the license if it's not at the top level, but
// inside another declaration?
@Test
public void testImportantCommentInTree() {
test(
"var a = function() {\n +" + "/*! Your favorite license goes here */\n" + " 1;};\n",
"/*\n Your favorite license goes here */\n",
null);
}
@Test
public void testMultipleUniqueImportantComments() {
String js1 = "/*! One license here */\n" + "var x;";
String js2 = "/*! Another license here */\n" + "var y;";
String expected = "/*\n One license here */\n" + "/*\n Another license here */\n";
Compiler compiler = new Compiler();
CompilerOptions options = createNewFlagBasedOptions();
List<SourceFile> inputs =
ImmutableList.of(
SourceFile.fromCode("testcode1", js1), SourceFile.fromCode("testcode2", js2));
Result result = compiler.compile(EMPTY_EXTERNS, inputs, options);
assertWithMessage(Joiner.on(",").join(result.errors)).that(result.success).isTrue();
assertThat(compiler.toSource()).isEqualTo(expected);
}
@Test
public void testMultipleIdenticalImportantComments() {
String js1 = "/*! Identical license here */\n" + "var x;";
String js2 = "/*! Identical license here */\n" + "var y;";
String expected = "/*\n Identical license here */\n";
Compiler compiler = new Compiler();
CompilerOptions options = createNewFlagBasedOptions();
List<SourceFile> inputs =
ImmutableList.of(
SourceFile.fromCode("testcode1", js1), SourceFile.fromCode("testcode2", js2));
Result result = compiler.compile(EMPTY_EXTERNS, inputs, options);
assertWithMessage(Joiner.on(",").join(result.errors)).that(result.success).isTrue();
assertThat(compiler.toSource()).isEqualTo(expected);
}
// Make sure we correctly output license text.
@Test
public void testLicenseDirectiveOutput() {
test(
"/** @license Your favorite license goes here */ var x;",
"/*\n Your favorite license goes here */\n",
null);
}
// Make sure we output license text even if followed by @fileoverview.
@Test
public void testLicenseAndOverviewDirectiveWarning() {
List<SourceFile> input =
ImmutableList.of(
SourceFile.fromCode(
"foo",
("/** @license Your favorite license goes here */\n"
+ "/** \n"
+ " * @fileoverview This is my favorite file! */\n"
+ "var x;")));
assertThat(new Compiler().compile(EMPTY_EXTERNS, input, new CompilerOptions()).success)
.isTrue();
}
// Text for the opposite order - @fileoverview, then @license.
@Test
public void testOverviewAndLicenseDirectiveOutput() {
test(
"/** @fileoverview This is my favorite file! */\n"
+ "/** @license Your favorite license goes here */\n"
+ "var x;",
"/*\n Your favorite license goes here */\n",
null);
}
// Test for sequence of @license and @fileoverview, and make sure
// all the licenses get copied over.
@Test
public void testLicenseOverviewLicense() {
test(
"/** @license Another license */\n"
+ "/** @fileoverview This is my favorite file! */\n"
+ "/** @license Your favorite license goes here */\n"
+ "var x;",
"/*\n Your favorite license goes here Another license */\n",
null);
}
// Make sure things work even with @license and @fileoverview in the
// same comment.
@Test
public void testCombinedLicenseOverviewDirectiveOutput() {
test(
"/** @license Your favorite license goes here\n"
+ " * @fileoverview This is my favorite file! */\n"
+ "var x;",
"/*\n Your favorite license goes here\n" + " @fileoverview This is my favorite file! */\n",
null);
}
// Does the presence of @author change anything with the license?
@Test
public void testCombinedLicenseAuthorDirectiveOutput() {
test(
"/** @license Your favorite license goes here\n" + " * @author Robert */\n" + "var x;",
"/*\n Your favorite license goes here\n @author Robert */\n",
null);
}
// Make sure we concatenate licenses the same way.
@Test
public void testMultipleLicenseDirectiveOutput() {
test(
lines(
"/** @license Your favorite license goes here */",
"/** @license Another license */",
"var x;"),
"/*\n Another license Your favorite license goes here */\n" ,
null);
}
// Same thing, two @licenses in the same comment.
@Test
public void testTwoLicenseInSameComment() {
test(
lines(
"/** @license Your favorite license goes here ",
" * @license Another license */",
"var x;"),
"/*\n Your favorite license goes here \n @license Another license */\n",
null);
}
// Do we correctly handle the license if it's not at the top level, but
// inside another declaration?
@Test
public void testLicenseInTree() {
test(
lines(
"var a = function() {",
"+ /** @license Your favorite license goes here */",
" 1;};"),
"/*\n Your favorite license goes here */\n",
null);
}
@Test
public void testMultipleUniqueLicenses() {
String js1 = "/** @license One license here */\n"
+ "var x;";
String js2 = "/** @license Another license here */\n"
+ "var y;";
String expected = "/*\n One license here */\n"
+ "/*\n Another license here */\n";
Compiler compiler = new Compiler();
CompilerOptions options = createNewFlagBasedOptions();
List<SourceFile> inputs = ImmutableList.of(
SourceFile.fromCode("testcode1", js1),
SourceFile.fromCode("testcode2", js2));
Result result = compiler.compile(EMPTY_EXTERNS, inputs, options);
assertWithMessage(Joiner.on(",").join(result.errors)).that(result.success).isTrue();
assertThat(compiler.toSource()).isEqualTo(expected);
}
@Test
public void testMultipleIdenticalLicenses() {
String js1 = "/** @license Identical license here */\n"
+ "var x;";
String js2 = "/** @license Identical license here */\n"
+ "var y;";
String js3 = "/** @license Identical license here */\n"
+ "var z;\n"
+ "/** @license Identical license here */";
String expected = "/*\n Identical license here */\n";
Compiler compiler = new Compiler();
CompilerOptions options = createNewFlagBasedOptions();
List<SourceFile> inputs = ImmutableList.of(
SourceFile.fromCode("testcode1", js1),
SourceFile.fromCode("testcode2", js2),
SourceFile.fromCode("bundled", js3));
Result result = compiler.compile(EMPTY_EXTERNS, inputs, options);
assertWithMessage(Joiner.on(",").join(result.errors)).that(result.success).isTrue();
assertThat(compiler.toSource()).isEqualTo(expected);
}
@Test
public void testIdenticalLicenseAndImportantComment() {
String js1 = "/** @license Identical license here */\n" + "var x;";
String js2 = "/*! Identical license here */\n" + "var y;";
String expected = "/*\n Identical license here */\n";
Compiler compiler = new Compiler();
CompilerOptions options = createNewFlagBasedOptions();
List<SourceFile> inputs =
ImmutableList.of(
SourceFile.fromCode("testcode1", js1), SourceFile.fromCode("testcode2", js2));
Result result = compiler.compile(EMPTY_EXTERNS, inputs, options);
assertWithMessage(Joiner.on(",").join(result.errors)).that(result.success).isTrue();
assertThat(compiler.toSource()).isEqualTo(expected);
}
@Test
public void testDefineNoOverriding() {
Map<String, Node> emptyMap = new HashMap<>();
List<String> defines = new ArrayList<>();
assertDefineOverrides(emptyMap, defines);
}
@Test
public void testDefineOverriding1() {
List<String> defines =
ImmutableList.of(
"COMPILED",
"DEF_TRUE=true",
"DEF_FALSE=false",
"DEF_NUMBER=5.5",
"DEF_STRING='bye'");
Map<String, Node> expected = ImmutableMap.of(
"COMPILED", new Node(Token.TRUE),
"DEF_TRUE", new Node(Token.TRUE),
"DEF_FALSE", new Node(Token.FALSE),
"DEF_NUMBER", Node.newNumber(5.5),
"DEF_STRING", Node.newString("bye"));
assertDefineOverrides(expected, defines);
}
@Test
public void testDefineOverriding2() {
List<String> defines = ImmutableList.of("DEF_STRING='='");
Map<String, Node> expected = ImmutableMap.of(
"DEF_STRING", Node.newString("="));
assertDefineOverrides(expected, defines);
}
@Test
public void testDefineOverriding3() {
List<String> defines = ImmutableList.of("a.DEBUG");
Map<String, Node> expected = ImmutableMap.of(
"a.DEBUG", new Node(Token.TRUE));
assertDefineOverrides(expected, defines);
}
@Test
public void testBadDefineOverriding1() {
List<String> defines = ImmutableList.of("DEF_STRING=");
assertCreateDefinesThrowsException(defines);
}
@Test
public void testBadDefineOverriding2() {
List<String> defines = ImmutableList.of("=true");
assertCreateDefinesThrowsException(defines);
}
@Test
public void testBadDefineOverriding3() {
List<String> defines = ImmutableList.of("DEF_STRING='''");
assertCreateDefinesThrowsException(defines);
}
static void assertCreateDefinesThrowsException(List<String> defines) {
try {
CompilerOptions options = new CompilerOptions();
AbstractCommandLineRunner.createDefineOrTweakReplacements(defines,
options, false);
} catch (RuntimeException e) {
return;
}
assertWithMessage(defines + " didn't fail").fail();
}
static void assertDefineOverrides(Map<String, Node> expected,
List<String> defines) {
CompilerOptions options = new CompilerOptions();
AbstractCommandLineRunner.createDefineOrTweakReplacements(defines, options,
false);
Map<String, Node> actual = options.getDefineReplacements();
// equality of nodes compares by reference, so instead,
// compare the maps manually using Node.checkTreeEqualsSilent
assertThat(actual).hasSize(expected.size());
for (Map.Entry<String, Node> entry : expected.entrySet()) {
assertWithMessage(entry.getKey()).that(actual.containsKey(entry.getKey())).isTrue();
Node actualNode = actual.get(entry.getKey());
assertWithMessage(entry.toString())
.that(entry.getValue().isEquivalentTo(actualNode))
.isTrue();
}
}
static Result test(String js, String expected, DiagnosticType error) {
Compiler compiler = new Compiler();
CompilerOptions options = createNewFlagBasedOptions();
List<SourceFile> inputs = ImmutableList.of(
SourceFile.fromCode("testcode", js));
Result result = compiler.compile(EMPTY_EXTERNS, inputs, options);
if (error == null) {
assertWithMessage(Joiner.on(",").join(result.errors)).that(result.success).isTrue();
String outputSource = compiler.toSource();
assertThat(outputSource).isEqualTo(expected);
} else {
assertThat(result.errors).hasSize(1);
assertThat(result.errors.get(0).getType()).isEqualTo(error);
}
return result;
}
@Test
public void testConsecutiveSemicolons() {
Compiler compiler = new Compiler();
CompilerOptions options = new CompilerOptions();
options.setEmitUseStrict(false);
compiler.initOptions(options);
String js = "if(a);";
Node n = compiler.parseTestCode(js);
Compiler.CodeBuilder cb = new Compiler.CodeBuilder();
compiler.toSource(cb, 0, n);
assertThat(cb.toString()).isEqualTo(js);
}
@Test
public void testWarningsFiltering() {
// Warnings and errors are left alone when no filtering is used
assertThat(hasOutput(null, "foo/bar.js", CheckLevel.WARNING)).isTrue();
assertThat(hasOutput(null, "foo/bar.js", CheckLevel.ERROR)).isTrue();
// Warnings (but not errors) get filtered out
assertThat(hasOutput("baz", "foo/bar.js", CheckLevel.WARNING)).isFalse();
assertThat(hasOutput("foo", "foo/bar.js", CheckLevel.WARNING)).isTrue();
assertThat(hasOutput("baz", "foo/bar.js", CheckLevel.ERROR)).isTrue();
assertThat(hasOutput("foo", "foo/bar.js", CheckLevel.ERROR)).isTrue();
}
@Test
public void testExportSymbolReservesNamesForRenameVars() {