-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
PureFunctionIdentifierTest.java
2930 lines (2605 loc) · 89.7 KB
/
PureFunctionIdentifierTest.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 2009 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 com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.testing.JSCompCorrespondences;
import com.google.javascript.rhino.Node;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for {@link PureFunctionIdentifier}
*
* @author johnlenz@google.com (John Lenz)
*/
@RunWith(JUnit4.class)
public final class PureFunctionIdentifierTest extends CompilerTestCase {
List<Node> noSideEffectCalls;
List<Node> localResultCalls;
boolean regExpHaveSideEffects = true;
private static final String TEST_EXTERNS =
CompilerTypeTestCase.DEFAULT_EXTERNS + lines(
"var window; window.setTimeout;",
"/**@nosideeffects*/ function externSENone(){}",
"/**@modifies{this}*/ function externSEThis(){}",
"/**@constructor",
" * @modifies{this}*/",
"function externObjSEThis(){}",
"/**",
" * @param {string} s id.",
" * @return {string}",
" * @modifies{this}",
" */",
"externObjSEThis.prototype.externObjSEThisMethod = function(s) {};",
"/**",
" * @param {string} s id.",
" * @return {string}",
" * @modifies{arguments}",
" */",
"externObjSEThis.prototype.externObjSEThisMethod2 = function(s) {};",
"/**@nosideeffects*/function Error(){}",
"function externSef1(){}",
"/**@nosideeffects*/function externNsef1(){}",
"var externSef2 = function(){};",
"/**@nosideeffects*/var externNsef2 = function(){};",
"var externNsef3 = /**@nosideeffects*/function(){};",
"var externObj;",
"externObj.sef1 = function(){};",
"/**@nosideeffects*/externObj.nsef1 = function(){};",
"externObj.nsef2 = /**@nosideeffects*/function(){};",
"externObj.partialFn;",
"externObj.partialSharedFn;",
"var externObj2;",
"externObj2.partialSharedFn = /**@nosideeffects*/function(){};",
"/**@constructor*/function externSefConstructor(){}",
"externSefConstructor.prototype.sefFnOfSefObj = function(){};",
"externSefConstructor.prototype.nsefFnOfSefObj = ",
" /**@nosideeffects*/function(){};",
"externSefConstructor.prototype.externShared = function(){};",
"/**@constructor@nosideeffects*/function externNsefConstructor(){}",
"externNsefConstructor.prototype.sefFnOfNsefObj = function(){};",
"externNsefConstructor.prototype.nsefFnOfNsefObj = ",
" /**@nosideeffects*/function(){};",
"externNsefConstructor.prototype.externShared = ",
" /**@nosideeffects*/function(){};",
"/**@constructor @nosideeffects*/function externNsefConstructor2(){}",
"externNsefConstructor2.prototype.externShared = ",
" /**@nosideeffects*/function(){};",
"externNsefConstructor.prototype.sharedPartialSef;",
"/**@nosideeffects*/externNsefConstructor.prototype.sharedPartialNsef;",
// An externs definition with a stub before.
"/**@constructor*/function externObj3(){}",
"externObj3.prototype.propWithStubBefore;",
"/**",
" * @param {string} s id.",
" * @return {string}",
" * @nosideeffects",
" */",
"externObj3.prototype.propWithStubBefore = function(s) {};",
// useless JsDoc
"/**",
" * @see {foo}",
" */",
"externObj3.prototype.propWithStubBeforeWithJSDoc;",
"/**",
" * @param {string} s id.",
" * @return {string}",
" * @nosideeffects",
" */",
"externObj3.prototype.propWithStubBeforeWithJSDoc = function(s) {};",
// An externs definition with a stub after.
"/**@constructor*/function externObj4(){}",
"/**",
" * @param {string} s id.",
" * @return {string}",
" * @nosideeffects",
" */",
"externObj4.prototype.propWithStubAfter = function(s) {};",
"externObj4.prototype.propWithStubAfter;",
"/**",
" * @param {string} s id.",
" * @return {string}",
" * @nosideeffects",
" */",
"externObj4.prototype.propWithStubAfterWithJSDoc = function(s) {};",
// useless JsDoc
"/**",
" * @see {foo}",
" */",
"externObj4.prototype.propWithStubAfterWithJSDoc;",
"var goog = {};",
"goog.reflect = {};",
"goog.reflect.cache = function(a, b, c, opt_d) {};",
"/** @nosideeffects */",
"externObj.prototype.duplicateExternFunc = function() {};",
"externObj2.prototype.duplicateExternFunc = function() {};",
"externObj.prototype['weirdDefinition'] = function() {};"
);
public PureFunctionIdentifierTest() {
super(TEST_EXTERNS);
}
@Override
protected int getNumRepetitions() {
// run pass once.
return 1;
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
enableNormalize();
enableGatherExternProperties();
enableTypeCheck();
}
@Override
@After
public void tearDown() throws Exception {
super.tearDown();
regExpHaveSideEffects = true;
}
/**
* Run PureFunctionIdentifier, then gather a list of calls that are marked as having no side
* effects.
*/
private class NoSideEffectCallEnumerator extends AbstractPostOrderCallback
implements CompilerPass {
private final Compiler compiler;
NoSideEffectCallEnumerator(Compiler compiler) {
this.compiler = compiler;
}
@Override
public void process(Node externs, Node root) {
noSideEffectCalls = new ArrayList<>();
localResultCalls = new ArrayList<>();
compiler.setHasRegExpGlobalReferences(regExpHaveSideEffects);
compiler.getOptions().setUseTypesForLocalOptimization(true);
new PureFunctionIdentifier.Driver(compiler).process(externs, root);
NodeTraversal.traverse(compiler, externs, this);
NodeTraversal.traverse(compiler, root, this);
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isNew()) {
if (!NodeUtil.constructorCallHasSideEffects(n)) {
noSideEffectCalls.add(n.getFirstChild());
}
} else if (NodeUtil.isInvocation(n)) {
if (!NodeUtil.functionCallHasSideEffects(n, compiler)) {
noSideEffectCalls.add(n.getFirstChild());
}
if (NodeUtil.callHasLocalResult(n)) {
localResultCalls.add(n.getFirstChild());
}
}
}
}
@Test
public void testIssue303() {
String source = lines(
"/** @constructor */ function F() {",
" var self = this;",
" window.setTimeout(function() {",
" window.location = self.location;",
" }, 0);",
"}",
"F.prototype.setLocation = function(x) {",
" this.location = x;",
"};",
"(new F()).setLocation('http://www.google.com/');"
);
assertNoPureCalls(source);
}
@Test
public void testIssue303b() {
String source = lines(
"/** @constructor */ function F() {",
" var self = this;",
" window.setTimeout(function() {",
" window.location = self.location;",
" }, 0);",
"}",
"F.prototype.setLocation = function(x) {",
" this.location = x;",
"};",
"function x() {",
" (new F()).setLocation('http://www.google.com/');",
"} window['x'] = x;"
);
assertNoPureCalls(source);
}
@Test
public void testAnnotationInExterns_new1() {
assertPureCallsMarked("externSENone()", ImmutableList.of("externSENone"));
}
@Test
public void testAnnotationInExterns_new2() {
assertNoPureCalls("externSEThis()");
}
@Test
public void testAnnotationInExterns_new3() {
assertPureCallsMarked("new externObjSEThis()", ImmutableList.of("externObjSEThis"));
}
@Test
public void testAnnotationInExterns_new4() {
// The entire expression containing "externObjSEThisMethod" is considered
// side-effect free in this context.
assertPureCallsMarked(
"new externObjSEThis().externObjSEThisMethod('')",
ImmutableList.of("externObjSEThis", "new externObjSEThis().externObjSEThisMethod"));
}
@Test
public void testAnnotationInExterns_new5() {
assertPureCallsMarked(
"function f() { new externObjSEThis() }; f();", ImmutableList.of("externObjSEThis", "f"));
}
@Test
public void testAnnotationInExterns_new6() {
// While "externObjSEThisMethod" has modifies "this"
// it does not have global side-effects with "this" is
// a known local value.
// TODO(johnlenz): "f" is side-effect free but we need
// to propagate that "externObjSEThisMethod" is modifying
// a local object.
String source = lines(
"function f() {",
" new externObjSEThis().externObjSEThisMethod('') ",
"};",
"f();"
);
assertPureCallsMarked(
source, ImmutableList.of("externObjSEThis", "new externObjSEThis().externObjSEThisMethod"));
}
@Test
public void testAnnotationInExterns_new7() {
// While "externObjSEThisMethod" has modifies "this"
// it does not have global side-effects with "this" is
// a known local value.
String source = lines(
"function f() {",
" var x = new externObjSEThis(); ",
" x.externObjSEThisMethod('') ",
"};",
"f();"
);
assertPureCallsMarked(source, ImmutableList.of("externObjSEThis"));
}
@Test
public void testAnnotationInExterns_new8() {
// "externObjSEThisMethod" modifies "this", the 'this'
// is not a known local value, so it must be assumed it is to
// have global side-effects.
String source = lines(
"function f(x) {",
" x.externObjSEThisMethod('') ",
"};",
"f(new externObjSEThis());"
);
assertPureCallsMarked(source, ImmutableList.of("externObjSEThis"));
}
@Test
public void testAnnotationInExterns_new9() {
// "externObjSEThisMethod" modifies "this", the 'this'
// is not a known local value, so it must be assumed it is to
// have global side-effects. All possible values of "x" are considered
// as no intraprocedural data flow is done.
String source = lines(
"function f(x) {",
" x = new externObjSEThis(); ",
" x.externObjSEThisMethod('') ",
"};",
"f(g);"
);
assertPureCallsMarked(source, ImmutableList.of("externObjSEThis"));
}
@Test
public void testAnnotationInExterns_new10() {
String source = lines(
"function f() {",
" new externObjSEThis().externObjSEThisMethod2('') ",
"};",
"f();"
);
assertPureCallsMarked(
source,
ImmutableList.of("externObjSEThis", "new externObjSEThis().externObjSEThisMethod2", "f"));
}
@Test
public void testAnnotationInExterns1() {
assertNoPureCalls("externSef1()");
}
@Test
public void testAnnotationInExterns2() {
assertNoPureCalls("externSef2()");
}
@Test
public void testAnnotationInExterns3() {
assertPureCallsMarked("externNsef1()", ImmutableList.of("externNsef1"));
}
@Test
public void testAnnotationInExterns4() {
assertPureCallsMarked("externNsef2()", ImmutableList.of("externNsef2"));
}
@Test
public void testAnnotationInExterns5() {
assertPureCallsMarked("externNsef3()", ImmutableList.of("externNsef3"));
}
@Test
public void testNamespaceAnnotationInExterns1() {
assertNoPureCalls("externObj.sef1()");
}
@Test
public void testNamespaceAnnotationInExterns2() {
assertPureCallsMarked("externObj.nsef1()", ImmutableList.of("externObj.nsef1"));
}
@Test
public void testNamespaceAnnotationInExterns3() {
assertPureCallsMarked("externObj.nsef2()", ImmutableList.of("externObj.nsef2"));
}
@Test
public void testNamespaceAnnotationInExterns4() {
assertNoPureCalls("externObj.partialFn()");
}
@Test
public void testNamespaceAnnotationInExterns5() {
// Test that adding a second definition for a partially defined
// function doesn't make us think that the function has no side
// effects.
String templateSrc = "var o = {}; o.<fnName> = function(){}; o.<fnName>()";
// Ensure that functions with name != "partialFn" get marked.
assertPureCallsMarked(
templateSrc.replace("<fnName>", "notPartialFn"), ImmutableList.of("o.notPartialFn"));
assertNoPureCalls(templateSrc.replace("<fnName>", "partialFn"));
}
@Test
public void testNamespaceAnnotationInExterns6() {
assertNoPureCalls("externObj.partialSharedFn()");
}
@Test
public void testConstructorAnnotationInExterns1() {
assertNoPureCalls("new externSefConstructor()");
}
@Test
public void testConstructorAnnotationInExterns2() {
String source = lines(
"var a = new externSefConstructor();",
"a.sefFnOfSefObj()");
assertNoPureCalls(source);
}
@Test
public void testConstructorAnnotationInExterns3() {
String source = lines(
"var a = new externSefConstructor();",
"a.nsefFnOfSefObj()");
assertPureCallsMarked(source, ImmutableList.of("a.nsefFnOfSefObj"));
}
@Test
public void testConstructorAnnotationInExterns4() {
String source = lines(
"var a = new externSefConstructor();",
"a.externShared()");
assertNoPureCalls(source);
}
@Test
public void testConstructorAnnotationInExterns5() {
assertPureCallsMarked("new externNsefConstructor()", ImmutableList.of("externNsefConstructor"));
}
@Test
public void testConstructorAnnotationInExterns6() {
String source = lines(
"var a = new externNsefConstructor();",
"a.sefFnOfNsefObj()");
assertPureCallsMarked(source, ImmutableList.of("externNsefConstructor"));
}
@Test
public void testConstructorAnnotationInExterns7() {
String source = lines(
"var a = new externNsefConstructor();",
"a.nsefFnOfNsefObj()");
assertPureCallsMarked(source, ImmutableList.of("externNsefConstructor", "a.nsefFnOfNsefObj"));
}
@Test
public void testConstructorAnnotationInExterns8() {
String source = lines(
"var a = new externNsefConstructor();",
"a.externShared()");
assertPureCallsMarked(source, ImmutableList.of("externNsefConstructor"));
}
@Test
public void testSharedFunctionName1() {
String source = lines(
"if (true) {",
" a = new externNsefConstructor()",
"} else {",
" a = new externSefConstructor()",
"}",
"a.externShared()");
assertPureCallsMarked(source, ImmutableList.of("externNsefConstructor"));
}
@Test
public void testSharedFunctionName2() {
// Implementation for both externNsefConstructor and externNsefConstructor2
// have no side effects.
boolean broken = true;
if (broken) {
assertPureCallsMarked(
lines(
"var a;",
"if (true) {",
" a = new externNsefConstructor()",
"} else {",
" a = new externNsefConstructor2()",
"}",
"a.externShared()"),
ImmutableList.of("externNsefConstructor", "externNsefConstructor2"));
} else {
assertPureCallsMarked(
lines(
"var a;",
"if (true) {",
" a = new externNsefConstructor()",
"} else {",
" a = new externNsefConstructor2()",
"}",
"a.externShared()"),
ImmutableList.of(
"externNsefConstructor", "externNsefConstructor2", "a.externShared"));
}
}
@Test
public void testAnnotationInExternStubs1() {
// In the case where a property is defined first as a stub and then with a FUNCTION:
// we have to make a conservative assumption about the behaviour of the extern, since the stub
// carried no information.
assertNoPureCalls("o.propWithStubBefore('a');");
}
@Test
public void testAnnotationInExternStubs1b() {
// In the case where a property is defined first as a stub and then with a FUNCTION:
// we have to make a conservative assumption about the behaviour of the extern, since the stub
// carried no information.
assertNoPureCalls("o.propWithStubBeforeWithJSDoc('a');");
}
@Test
public void testAnnotationInExternStubs2() {
// In the case where a property is defined first with a FUNCTION and then as a stub:
// we have to make a conservative assumption about the behaviour of the extern, since the stub
// carried no information.
assertNoPureCalls("o.propWithStubAfter('a');");
}
@Test
public void testAnnotationInExternStubs3() {
// In the case where a property is defined first with a FUNCTION and then as a stub:
// we have to make a conservative assumption about the behaviour of the extern, since the stub
// carried no information.
assertNoPureCalls("propWithAnnotatedStubAfter('a');");
}
@Test
public void testAnnotationInExternStubs4() {
// An externs definition with a stub that differs from the declaration.
// Verify our assumption is valid about this.
String externs = lines(
"/**@constructor*/function externObj5(){}",
"externObj5.prototype.propWithAnnotatedStubAfter = function(s) {};",
"/**",
" * @param {string} s id.",
" * @return {string}",
" * @nosideeffects",
" */",
"externObj5.prototype.propWithAnnotatedStubAfter;");
enableTypeCheck();
testSame(
externs(externs),
srcs("o.prototype.propWithAnnotatedStubAfter"),
warning(TypeValidator.DUP_VAR_DECLARATION_TYPE_MISMATCH));
assertThat(noSideEffectCalls).isEmpty();
}
@Test
public void testAnnotationInExternStubs5() {
// An externs definition with a stub that differs from the declaration.
// Verify our assumption is valid about this.
String externs = lines(
"/**@constructor*/function externObj5(){}",
"/**",
" * @param {string} s id.",
" * @return {string}",
" * @nosideeffects",
" */",
"externObj5.prototype.propWithAnnotatedStubAfter = function(s) {};",
"/**",
" * @param {string} s id.",
" * @return {string}",
" */",
"externObj5.prototype.propWithAnnotatedStubAfter;");
enableTypeCheck();
testSame(
externs(externs),
srcs("o.prototype.propWithAnnotatedStubAfter"),
warning(TypeValidator.DUP_VAR_DECLARATION));
assertThat(noSideEffectCalls).isEmpty();
}
@Test
public void testNoSideEffectsSimple() {
String prefix = "function f(){";
String suffix = "} f()";
List<String> expected = ImmutableList.of("f");
assertPureCallsMarked(
prefix + "" + suffix, expected);
assertPureCallsMarked(
prefix + "return 1" + suffix, expected);
assertPureCallsMarked(
prefix + "return 1 + 2" + suffix, expected);
// local var
assertPureCallsMarked(
prefix + "var a = 1; return a" + suffix, expected);
// mutate local var
assertPureCallsMarked(
prefix + "var a = 1; a = 2; return a" + suffix, expected);
assertPureCallsMarked(
prefix + "var a = 1; a = 2; return a + 1" + suffix, expected);
// read from obj literal
assertPureCallsMarked(
prefix + "var a = {foo : 1}; return a.foo" + suffix, expected);
assertPureCallsMarked(
prefix + "var a = {foo : 1}; return a.foo + 1" + suffix, expected);
// read from extern
assertPureCallsMarked(
prefix + "return externObj" + suffix, expected);
assertPureCallsMarked(
"function g(x) { x.foo = 3; }" /* to suppress missing property */
+ prefix + "return externObj.foo" + suffix, expected);
}
@Test
public void testNoSideEffectsSimple2() {
regExpHaveSideEffects = false;
String source = lines(
"function f() {",
" return ''.replace(/xyz/g, '');",
"}",
"f()");
assertPureCallsMarked(source, ImmutableList.of("''.replace", "f"));
}
@Test
public void testNoSideEffectsSimple3() {
regExpHaveSideEffects = false;
String source =
lines(
"function f(/** string */ x) {", //
" return x.replace(/xyz/g, '');",
"}",
"f('')");
assertPureCallsMarked(source, ImmutableList.of("x.replace", "f"));
}
@Test
public void testResultLocalitySimple() {
String prefix = "var g; function f(){";
String suffix = "} f()";
final List<String> fReturnsUnescaped = ImmutableList.of("f");
final List<String> fReturnsEscaped = ImmutableList.of();
// no return
assertUnescapedReturnCallsMarked(prefix + "" + suffix, fReturnsUnescaped);
// simple return expressions
assertUnescapedReturnCallsMarked(prefix + "return 1" + suffix, fReturnsUnescaped);
assertUnescapedReturnCallsMarked(prefix + "return 1 + 2" + suffix, fReturnsUnescaped);
// global result
assertUnescapedReturnCallsMarked(prefix + "return g" + suffix, fReturnsEscaped);
// multiple returns
assertUnescapedReturnCallsMarked(prefix + "return 1; return 2" + suffix, fReturnsUnescaped);
assertUnescapedReturnCallsMarked(prefix + "return 1; return g" + suffix, fReturnsEscaped);
// local var, not yet. Note we do not handle locals properly here.
assertUnescapedReturnCallsMarked(prefix + "var a = 1; return a" + suffix, fReturnsEscaped);
// mutate local var, not yet. Note we do not handle locals properly here.
assertUnescapedReturnCallsMarked(
prefix + "var a = 1; a = 2; return a" + suffix, fReturnsEscaped);
assertUnescapedReturnCallsMarked(
prefix + "var a = 1; a = 2; return a + 1" + suffix, fReturnsUnescaped);
// read from obj literal
assertUnescapedReturnCallsMarked(prefix + "return {foo : 1}.foo" + suffix, fReturnsEscaped);
assertUnescapedReturnCallsMarked(
prefix + "var a = {foo : 1}; return a.foo" + suffix, fReturnsEscaped);
// read from extern
assertUnescapedReturnCallsMarked(prefix + "return externObj" + suffix, ImmutableList.of());
assertUnescapedReturnCallsMarked(
"function inner(x) { x.foo = 3; }" /* to suppress missing property */
+ prefix
+ "return externObj.foo"
+ suffix,
ImmutableList.of());
}
@Test
public void testReturnLocalityTaintObjectLiteralWithGlobal() {
// return empty object literal. This is completely local
String source = lines(
"function f() { return {} }",
"f();"
);
assertUnescapedReturnCallsMarked(source, ImmutableList.of("f"));
// return obj literal with global property is still local.
source = lines(
"var global = new Object();",
"function f() { return {'asdf': global} }",
"f();");
assertUnescapedReturnCallsMarked(source, ImmutableList.of("f"));
}
@Test
public void testReturnLocalityTaintArrayLiteralWithGlobal() {
String source =
lines(
"function f() { return []; }",
"f();",
"function g() { return [1, {}]; }",
"g();");
assertUnescapedReturnCallsMarked(source, ImmutableList.of("f", "g"));
// return array literal with global value is still a local value.
source =
lines(
"var global = new Object();",
"function f() { return [2 ,global]; }",
"f();");
assertUnescapedReturnCallsMarked(source, ImmutableList.of("f"));
}
@Test
public void testReturnLocalityMultipleDefinitionsSameName() {
String source = lines(
"var global = new Object();",
"A.func = function() {return global}", // return global (taintsReturn)
"B.func = function() {return 1; }", // returns local
"C.func();");
assertUnescapedReturnCallsMarked(source, ImmutableList.of());
}
@Test
public void testExternCalls() {
testExternCallsForTypeInferenceMode(/* typeChecked= */ true);
}
@Test
public void testExternCallsNoTypeChecking() {
testExternCallsForTypeInferenceMode(/* typeChecked= */ false);
}
private void testExternCallsForTypeInferenceMode(boolean typeChecked) {
if (typeChecked) {
enableTypeCheck();
} else {
disableTypeCheck();
}
String prefix = "function f(){";
String suffix = "} f()";
assertPureCallsMarked(prefix + "externNsef1()" + suffix,
ImmutableList.of("externNsef1", "f"));
assertPureCallsMarked(prefix + "externObj.nsef1()" + suffix,
ImmutableList.of("externObj.nsef1", "f"));
assertUnescapedReturnCallsMarked("externNsef1(); externObj.nsef1()", ImmutableList.of());
assertNoPureCalls(prefix + "externSef1()" + suffix);
assertNoPureCalls(prefix + "externObj.sef1()" + suffix);
}
@Test
public void testApply() {
String source = lines(
"function f() {return 42}",
"f.apply(null)");
assertPureCallsMarked(source, ImmutableList.of("f.apply"));
}
@Test
public void testCall() {
String source = lines(
"function f() {return 42}",
"f.call(null)");
assertPureCallsMarked(source, ImmutableList.of("f.call"));
}
@Test
public void testApplyToUnknownDefinition() {
String source = lines(
"var dict = {'func': function() {}};",
"function f() { var s = dict['func'];}",
"f.apply(null)"
);
assertPureCallsMarked(source, ImmutableList.of("f.apply"));
// Not marked because the definition cannot be found so unknown side effects.
source = lines(
"var dict = {'func': function() {}};",
"function f() { var s = dict['func'].apply(null); }",
"f.apply(null)"
);
assertNoPureCalls(source);
// Not marked because the definition cannot be found so unknown side effects.
source = lines(
"var pure = function() {};",
"var dict = {'func': function() {}};",
"function f() { var s = (dict['func'] || pure)();}",
"f()"
);
assertNoPureCalls(source);
// Not marked because the definition cannot be found so unknown side effects.
source = lines(
"var pure = function() {};"
, "var dict = {'func': function() {}};"
, "function f() { var s = (condition ? dict['func'] : pure)();}"
, "f()"
);
assertNoPureCalls(source);
}
@Test
public void testInference1() {
String source = lines(
"function f() {return g()}",
"function g() {return 42}",
"f()"
);
assertPureCallsMarked(source, ImmutableList.of("g", "f"));
}
@Test
public void testInference2() {
String source = lines(
"var a = 1;",
"function f() {g()}",
"function g() {a=2}",
"f()"
);
assertNoPureCalls(source);
}
@Test
public void testInference3() {
String source = lines(
"var f = function() {return g()};",
"var g = function() {return 42};",
"f()"
);
assertPureCallsMarked(source, ImmutableList.of("g", "f"));
}
@Test
public void testInference4() {
String source = lines(
"var a = 1; var f = function() {g()};",
"var g = function() {a=2};",
"f()"
);
assertNoPureCalls(source);
}
@Test
public void testInference5() {
String source = lines(
"goog.f = function() {return goog.g()};",
"goog.g = function() {return 42};",
"goog.f()"
);
assertPureCallsMarked(source, ImmutableList.of("goog.g", "goog.f"));
}
@Test
public void testInference6() {
String source = lines(
"var a = 1;",
"goog.f = function() {goog.g()};",
"goog.g = function() {a=2};",
"goog.f()"
);
assertNoPureCalls(source);
}
@Test
public void testLocalizedSideEffects1() {
// Returning a function that contains a modification of a local
// is not a global side-effect.
String source = lines(
"function f() {",
" var x = {foo : 0}; return function() {x.foo++};",
"}",
"f()"
);
assertPureCallsMarked(source, ImmutableList.of("f"));
}
@Test
public void testLocalizedSideEffects2() {
// Calling a function that contains a modification of a local
// is a global side-effect (the value has escaped).
String source = lines(
"function f() {",
" var x = {foo : 0}; (function() {x.foo++})();",
"}",
"f()"
);
assertNoPureCalls(source);
}
@Test
public void testLocalizedSideEffects3() {
// A local that might be assigned a global value and whose properties
// are modified must be considered a global side-effect.
String source = lines(
"var g = {foo:1};",
"function f() {var x = g; x.foo++};",
"f();"
);
assertNoPureCalls(source);
}
@Test
public void testLocalizedSideEffects4() {
// An array is a local object, assigning a local array is not a global side-effect.
assertPureCallsMarked(
lines(
"function f() {var x = []; x[0] = 1;}", // preserve newline
"f()"),
ImmutableList.of("f"));
// TODO(bradfordcsmith): Remove NEITHER when type checker understands let/const
disableTypeCheck();
assertPureCallsMarked(
lines(
"function f() {const x = []; x[0] = 1;}", // preserve newline
"f()"),
ImmutableList.of("f"));
}
@Test
public void testLocalizedSideEffects5() {
// Assigning a local alias of a global is a global
// side-effect.
String source = lines(
"var g = [];",
"function f() {var x = g; x[0] = 1;};",