-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
PureFunctionIdentifierTest.java
2089 lines (1813 loc) · 67.9 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.rhino.Node;
import java.util.ArrayList;
import java.util.List;
/**
* Tests for {@link PureFunctionIdentifier}
*
* @author johnlenz@google.com (John Lenz)
*/
public final class PureFunctionIdentifierTest extends TypeICompilerTestCase {
List<String> noSideEffectCalls;
List<String> 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
protected void setUp() throws Exception {
super.setUp();
ignoreWarnings(NewTypeInference.GLOBAL_THIS, NewTypeInference.INEXISTENT_PROPERTY);
}
@Override
protected 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);
NameBasedDefinitionProvider defFinder = new NameBasedDefinitionProvider(compiler, true);
defFinder.process(externs, root);
PureFunctionIdentifier pureFunctionIdentifier =
new PureFunctionIdentifier(compiler, defFinder);
pureFunctionIdentifier.process(externs, root);
// Ensure that debug report computation doesn't crash.
pureFunctionIdentifier.getDebugReport();
NodeTraversal.traverseEs6(compiler, externs, this);
NodeTraversal.traverseEs6(compiler, root, this);
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isNew()) {
if (!NodeUtil.constructorCallHasSideEffects(n)) {
noSideEffectCalls.add(generateNameString(n.getFirstChild()));
}
} else if (n.isCall()) {
if (!NodeUtil.functionCallHasSideEffects(n, compiler)) {
noSideEffectCalls.add(generateNameString(n.getFirstChild()));
}
if (NodeUtil.callHasLocalResult(n)) {
localResultCalls.add(generateNameString(n.getFirstChild()));
}
}
}
private String generateNameString(Node node) {
if (node.isOr()) {
return "(" + generateNameString(node.getFirstChild())
+ " || " + generateNameString(node.getLastChild()) + ")";
} else if (node.isHook()) {
return "(" + generateNameString(node.getSecondChild())
+ " : " + generateNameString(node.getLastChild()) + ")";
} else {
String result = node.getQualifiedName();
if (result == null) {
if (node.isFunction()) {
result = node.toString(false, false, false).trim();
} else {
result = node.getFirstChild().toString(false, false, false);
result += " " + node.getLastChild().toString(false, false, false);
}
}
return result;
}
}
}
public void testIssue303() throws Exception {
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);
}
public void testIssue303b() throws Exception {
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);
}
public void testAnnotationInExterns_new1() throws Exception {
assertPureCallsMarked("externSENone()", ImmutableList.of("externSENone"));
}
public void testAnnotationInExterns_new2() throws Exception {
assertNoPureCalls("externSEThis()");
}
public void testAnnotationInExterns_new3() throws Exception {
assertPureCallsMarked("new externObjSEThis()", ImmutableList.of("externObjSEThis"));
}
public void testAnnotationInExterns_new4() throws Exception {
// The entire expression containing "externObjSEThisMethod" is considered
// side-effect free in this context.
assertPureCallsMarked("new externObjSEThis().externObjSEThisMethod('')",
ImmutableList.of("externObjSEThis", "NEW STRING externObjSEThisMethod"));
}
public void testAnnotationInExterns_new5() throws Exception {
assertPureCallsMarked(
"function f() { new externObjSEThis() }; f();", ImmutableList.of("externObjSEThis", "f"));
}
public void testAnnotationInExterns_new6() throws Exception {
// 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 STRING externObjSEThisMethod"));
}
public void testAnnotationInExterns_new7() throws Exception {
// 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"));
}
public void testAnnotationInExterns_new8() throws Exception {
// "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"));
}
public void testAnnotationInExterns_new9() throws Exception {
// "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"));
}
public void testAnnotationInExterns_new10() throws Exception {
String source = lines(
"function f() {",
" new externObjSEThis().externObjSEThisMethod2('') ",
"};",
"f();"
);
assertPureCallsMarked(source,
ImmutableList.of("externObjSEThis", "NEW STRING externObjSEThisMethod2", "f"));
}
public void testAnnotationInExterns1() throws Exception {
assertNoPureCalls("externSef1()");
}
public void testAnnotationInExterns2() throws Exception {
assertNoPureCalls("externSef2()");
}
public void testAnnotationInExterns3() throws Exception {
assertPureCallsMarked("externNsef1()", ImmutableList.of("externNsef1"));
}
public void testAnnotationInExterns4() throws Exception {
assertPureCallsMarked("externNsef2()", ImmutableList.of("externNsef2"));
}
public void testAnnotationInExterns5() throws Exception {
assertPureCallsMarked("externNsef3()", ImmutableList.of("externNsef3"));
}
public void testNamespaceAnnotationInExterns1() throws Exception {
assertNoPureCalls("externObj.sef1()");
}
public void testNamespaceAnnotationInExterns2() throws Exception {
assertPureCallsMarked("externObj.nsef1()", ImmutableList.of("externObj.nsef1"));
}
public void testNamespaceAnnotationInExterns3() throws Exception {
assertPureCallsMarked("externObj.nsef2()", ImmutableList.of("externObj.nsef2"));
}
public void testNamespaceAnnotationInExterns4() throws Exception {
assertNoPureCalls("externObj.partialFn()");
}
public void testNamespaceAnnotationInExterns5() throws Exception {
// 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"));
}
public void testNamespaceAnnotationInExterns6() throws Exception {
assertNoPureCalls("externObj.partialSharedFn()");
}
public void testConstructorAnnotationInExterns1() throws Exception {
assertNoPureCalls("new externSefConstructor()");
}
public void testConstructorAnnotationInExterns2() throws Exception {
String source = lines(
"var a = new externSefConstructor();",
"a.sefFnOfSefObj()");
assertNoPureCalls(source);
}
public void testConstructorAnnotationInExterns3() throws Exception {
String source = lines(
"var a = new externSefConstructor();",
"a.nsefFnOfSefObj()");
assertPureCallsMarked(source, ImmutableList.of("a.nsefFnOfSefObj"));
}
public void testConstructorAnnotationInExterns4() throws Exception {
String source = lines(
"var a = new externSefConstructor();",
"a.externShared()");
assertNoPureCalls(source);
}
public void testConstructorAnnotationInExterns5() throws Exception {
assertPureCallsMarked("new externNsefConstructor()", ImmutableList.of("externNsefConstructor"));
}
public void testConstructorAnnotationInExterns6() throws Exception {
String source = lines(
"var a = new externNsefConstructor();",
"a.sefFnOfNsefObj()");
assertPureCallsMarked(source, ImmutableList.of("externNsefConstructor"));
}
public void testConstructorAnnotationInExterns7() throws Exception {
String source = lines(
"var a = new externNsefConstructor();",
"a.nsefFnOfNsefObj()");
assertPureCallsMarked(source, ImmutableList.of("externNsefConstructor", "a.nsefFnOfNsefObj"));
}
public void testConstructorAnnotationInExterns8() throws Exception {
String source = lines(
"var a = new externNsefConstructor();",
"a.externShared()");
assertPureCallsMarked(source, ImmutableList.of("externNsefConstructor"));
}
public void testSharedFunctionName1() throws Exception {
String source = lines(
"if (true) {",
" a = new externNsefConstructor()",
"} else {",
" a = new externSefConstructor()",
"}",
"a.externShared()");
assertPureCallsMarked(source, ImmutableList.of("externNsefConstructor"));
}
public void testSharedFunctionName2() throws Exception {
// 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"));
}
}
public void testAnnotationInExternStubs1() throws Exception {
assertPureCallsMarked("o.propWithStubBefore('a');",
ImmutableList.of("o.propWithStubBefore"));
}
public void testAnnotationInExternStubs1b() throws Exception {
assertPureCallsMarked("o.propWithStubBeforeWithJSDoc('a');",
ImmutableList.of("o.propWithStubBeforeWithJSDoc"));
}
public void testAnnotationInExternStubs2() throws Exception {
assertPureCallsMarked("o.propWithStubAfter('a');",
ImmutableList.of("o.propWithStubAfter"));
}
public void testAnnotationInExternStubs3() throws Exception {
assertNoPureCalls("propWithAnnotatedStubAfter('a');");
}
public void testAnnotationInExternStubs4() throws Exception {
// 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;");
this.mode = TypeInferenceMode.OTI_ONLY;
testSame(
externs,
"o.prototype.propWithAnnotatedStubAfter",
TypeValidator.DUP_VAR_DECLARATION_TYPE_MISMATCH);
assertThat(noSideEffectCalls).isEmpty();
this.mode = TypeInferenceMode.NTI_ONLY;
testSame(
TEST_EXTERNS + externs,
"o.prototype.propWithAnnotatedStubAfter",
GlobalTypeInfoCollector.REDECLARED_PROPERTY);
assertThat(noSideEffectCalls).isEmpty();
}
public void testAnnotationInExternStubs5() throws Exception {
// 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;");
this.mode = TypeInferenceMode.OTI_ONLY;
testSame(externs,
"o.prototype.propWithAnnotatedStubAfter",
TypeValidator.DUP_VAR_DECLARATION);
assertThat(noSideEffectCalls).isEmpty();
this.mode = TypeInferenceMode.NTI_ONLY;
testSame(TEST_EXTERNS + externs,
"o.prototype.propWithAnnotatedStubAfter",
GlobalTypeInfoCollector.REDECLARED_PROPERTY);
assertThat(noSideEffectCalls).isEmpty();
}
public void testNoSideEffectsSimple() throws Exception {
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);
}
public void testNoSideEffectsSimple2() throws Exception {
regExpHaveSideEffects = false;
String source = lines(
"function f() {",
" return ''.replace(/xyz/g, '');",
"}",
"f()");
assertPureCallsMarked(source, ImmutableList.of("STRING STRING replace", "f"));
}
public void testNoSideEffectsSimple3() throws Exception {
regExpHaveSideEffects = false;
String source = lines(
"function f(/** string */ str) {",
" return str.replace(/xyz/g, '');",
"}",
"f('')");
assertPureCallsMarked(source, ImmutableList.of("str.replace", "f"));
}
public void testResultLocalitySimple() throws Exception {
String prefix = "var g; function f(){";
String suffix = "} f()";
final List<String> fReturnsLocal = ImmutableList.of("f");
final List<String> fReturnsNonLocal = ImmutableList.<String>of();
// no return
checkLocalityOfMarkedCalls(prefix + "" + suffix, fReturnsLocal);
// simple return expressions
checkLocalityOfMarkedCalls(prefix + "return 1" + suffix, fReturnsLocal);
checkLocalityOfMarkedCalls(prefix + "return 1 + 2" + suffix, fReturnsLocal);
// global result
checkLocalityOfMarkedCalls(prefix + "return g" + suffix, fReturnsNonLocal);
// multiple returns
checkLocalityOfMarkedCalls(prefix + "return 1; return 2" + suffix, fReturnsLocal);
checkLocalityOfMarkedCalls(prefix + "return 1; return g" + suffix, fReturnsNonLocal);
// local var, not yet. Note we do not handle locals properly here.
checkLocalityOfMarkedCalls(prefix + "var a = 1; return a" + suffix, fReturnsNonLocal);
// mutate local var, not yet. Note we do not handle locals properly here.
checkLocalityOfMarkedCalls(prefix + "var a = 1; a = 2; return a" + suffix, fReturnsNonLocal);
checkLocalityOfMarkedCalls(prefix + "var a = 1; a = 2; return a + 1" + suffix, fReturnsLocal);
// read from obj literal
checkLocalityOfMarkedCalls(prefix + "return {foo : 1}.foo" + suffix, fReturnsNonLocal);
checkLocalityOfMarkedCalls(
prefix + "var a = {foo : 1}; return a.foo" + suffix, fReturnsNonLocal);
// read from extern
checkLocalityOfMarkedCalls(prefix + "return externObj" + suffix, ImmutableList.<String>of());
checkLocalityOfMarkedCalls(
"function inner(x) { x.foo = 3; }" /* to suppress missing property */
+ prefix + "return externObj.foo" + suffix, ImmutableList.<String>of());
}
public void testReturnLocalityTaintObjectLiteralWithGlobal() {
// return empty object literal. This is completely local
String source = lines(
"function f() { return {} }",
"f();"
);
checkLocalityOfMarkedCalls(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();");
checkLocalityOfMarkedCalls(source, ImmutableList.<String>of("f"));
}
public void testReturnLocalityTaintArrayLiteralWithGlobal() {
String source =
lines(
"function f() { return []; }",
"f();",
"function g() { return [1, {}]; }",
"g();");
checkLocalityOfMarkedCalls(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();");
checkLocalityOfMarkedCalls(source, ImmutableList.<String>of("f"));
}
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();");
checkLocalityOfMarkedCalls(source, ImmutableList.<String>of());
}
public void testExternCalls() throws Exception {
testExternCallsForTypeInferenceMode(TypeInferenceMode.BOTH);
}
public void testExternCallsNoTypeChecking() throws Exception {
testExternCallsForTypeInferenceMode(TypeInferenceMode.NEITHER);
}
private void testExternCallsForTypeInferenceMode(TypeInferenceMode typeInferenceMode) {
mode = typeInferenceMode;
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"));
checkLocalityOfMarkedCalls("externNsef1(); externObj.nsef1()", ImmutableList.of());
assertNoPureCalls(prefix + "externSef1()" + suffix);
assertNoPureCalls(prefix + "externObj.sef1()" + suffix);
}
public void testApply() throws Exception {
String source = lines(
"function f() {return 42}",
"f.apply(null)");
assertPureCallsMarked(source, ImmutableList.of("f.apply"));
}
public void testCall() throws Exception {
String source = lines(
"function f() {return 42}",
"f.call(null)");
assertPureCallsMarked(source, ImmutableList.of("f.call"));
}
public void testApplyToUnknownDefinition() throws Exception {
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);
}
public void testInference1() throws Exception {
String source = lines(
"function f() {return g()}",
"function g() {return 42}",
"f()"
);
assertPureCallsMarked(source, ImmutableList.of("g", "f"));
}
public void testInference2() throws Exception {
String source = lines(
"var a = 1;",
"function f() {g()}",
"function g() {a=2}",
"f()"
);
assertNoPureCalls(source);
}
public void testInference3() throws Exception {
String source = lines(
"var f = function() {return g()};",
"var g = function() {return 42};",
"f()"
);
assertPureCallsMarked(source, ImmutableList.of("g", "f"));
}
public void testInference4() throws Exception {
String source = lines(
"var a = 1; var f = function() {g()};",
"var g = function() {a=2};",
"f()"
);
assertNoPureCalls(source);
}
public void testInference5() throws Exception {
String source = lines(
"goog.f = function() {return goog.g()};",
"goog.g = function() {return 42};",
"goog.f()"
);
assertPureCallsMarked(source, ImmutableList.of("goog.g", "goog.f"));
}
public void testInference6() throws Exception {
String source = lines(
"var a = 1;",
"goog.f = function() {goog.g()};",
"goog.g = function() {a=2};",
"goog.f()"
);
assertNoPureCalls(source);
}
public void testLocalizedSideEffects1() throws Exception {
// 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"));
}
public void testLocalizedSideEffects2() throws Exception {
// 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);
}
public void testLocalizedSideEffects3() throws Exception {
// 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);
}
public void testLocalizedSideEffects4() throws Exception {
// 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
mode = TypeInferenceMode.NEITHER;
assertPureCallsMarked(
lines(
"function f() {const x = []; x[0] = 1;}", // preserve newline
"f()"),
ImmutableList.of("f"));
}
public void testLocalizedSideEffects5() throws Exception {
// 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;};",
"f()"
);
assertNoPureCalls(source);
}
public void testLocalizedSideEffects6() throws Exception {
// Returning a local object that has been modified
// is not a global side-effect.
assertPureCallsMarked(
lines(
"function f() {", // preserve newline
" var x = {}; x.foo = 1; return x;",
"}",
"f()"),
ImmutableList.of("f"));
// TODO(bradfordcsmith): Remove NEITHER when type checker understands let/const
mode = TypeInferenceMode.NEITHER;
assertPureCallsMarked(
lines(
"function f() {", // preserve newline
" const x = {}; x.foo = 1; return x;",
"}",
"f()"),
ImmutableList.of("f"));
}
public void testLocalizedSideEffects7() throws Exception {
// Returning a local object that has been modified
// is not a global side-effect.
assertPureCallsMarked(
lines(
"/** @constructor A */ function A() {};",
"function f() {",
" var a = []; a[1] = 1; return a;",
"}",
"f()"),
ImmutableList.of("f"));
// TODO(bradfordcsmith): Remove NEITHER when type checker understands let/const
mode = TypeInferenceMode.NEITHER;
assertPureCallsMarked(
lines(
"/** @constructor A */ function A() {};",
"function f() {",
" const a = []; a[1] = 1; return a;",
"}",
"f()"),
ImmutableList.of("f"));
}
public void testLocalizedSideEffects8() throws Exception {
// Returning a local object that has been modified