forked from cppcheck-opensource/cppcheck
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestdataflow.cpp
More file actions
3587 lines (3334 loc) · 190 KB
/
Copy pathtestdataflow.cpp
File metadata and controls
3587 lines (3334 loc) · 190 KB
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
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2026 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Test suite for the DataFlow analysis (lib/dataflow.cpp).
*
* Design rules for this file:
*
* - Every test corresponds to exactly one task from the implementation plan.
* - Each test must FAIL before the fix is applied and PASS after.
* - The analysis is run at CheckLevel::normal (the level DataFlow is active).
* - Tests look for token "x" at a specific source line and check its values.
* - False-positive regression tests are added as trac tickets are resolved;
* those tests verify that the analysis does NOT report a value.
*
* Helper methods:
* - testValueOfXKnown(code, linenr, value) → x has Known integer value
* - testValueOfXPossible(code, linenr, value) → x has Possible integer value
* - testValueOfXImpossible(code, linenr, value) → x has Impossible integer value
* - testValueOfXNone(code, linenr) → x has no values at all
*/
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "mathlib.h"
#include "settings.h"
#include "token.h"
#include "vfvalue.h"
#include <algorithm>
#include <cmath>
#include <functional>
#include <list>
#include <sstream>
#include <string>
class TestDataFlow : public TestFixture {
public:
TestDataFlow() : TestFixture("TestDataFlow") {}
private:
// Settings with CheckLevel::normal so DataFlow (not ValueFlow) is used.
// Requirement: the new analysis runs at normal check level.
/*const*/ Settings settings = settingsBuilder().checkLevel(Settings::CheckLevel::normal).build();
void run() override {
// Phase 1 — Forward: basic integer constant tracking
TEST_CASE(constantPropagation);
// Phase 2 — Forward: arithmetic and constant folding
TEST_CASE(arithmetic);
// Phase 3 — Forward: branches (if/else)
TEST_CASE(forwardBranches);
// Phase 4 — Forward: loops
TEST_CASE(forwardLoops);
// Phase 5 — Forward: function calls (conservative)
TEST_CASE(forwardFunctionCalls);
// Phase B1 — Backward: basic constraint propagation
TEST_CASE(backwardConstraints);
// Phase R — Relational operator constraints (< > <= >=)
TEST_CASE(relationalConstraints);
// Phase OT — Operator token value annotation
TEST_CASE(operatorTokenValues);
// Phase UI — Unsigned integer impossible-value constraints
TEST_CASE(unsignedImpossible);
// Phase SW — Switch/case value propagation
TEST_CASE(switchVariable);
// Phase LB — For-loop variable bounds inside loop body
TEST_CASE(loopBounds);
// Phase BW — Bitwise operation value annotation
TEST_CASE(bitwiseOps);
// Phase TT — Type truncation on assignment
TEST_CASE(typeTruncation);
// Robustness: no crash or hang on pathological inputs
TEST_CASE(nocrash);
// Phase 6 — Complexity abort: no false positives
TEST_CASE(complexityAbort);
// Phase N — Null pointer tracking
TEST_CASE(nullPointer);
// Phase U — Uninitialized variable tracking
TEST_CASE(uninitVariable);
// Phase F — Float/double value tracking
TEST_CASE(floatPropagation);
// Phase S — String literal non-null tracking
TEST_CASE(stringLiteralNonNull);
// Phase U2 — Enhanced uninit tracking (survives function calls)
TEST_CASE(uninitAfterCall);
// Phase M — Struct/class member field tracking
TEST_CASE(memberFieldPropagation);
// Phase M2 — Member-access expression carries the field value
// (the '.' token must be annotated so division-by-zero checkers find it)
TEST_CASE(memberFieldDivisionByZero);
// Phase MN — Struct member pointer null condition constraints
TEST_CASE(memberPtrCondition);
// Phase C — Container size tracking
TEST_CASE(containerSize);
// Phase Cast — Cast expression value propagation
TEST_CASE(castValuePropagation);
// Literal constant annotation — integer/float literals must be annotated
// with their Known values so that checkers (checkZeroDivision, arrayIndex)
// can find them via getValue() in normal check level.
TEST_CASE(literalAnnotation);
// False-positive regression tests (grows as trac tickets are resolved)
TEST_CASE(falsePositiveRegression);
}
// -----------------------------------------------------------------------
// Helpers
// -----------------------------------------------------------------------
// removeImpossible: filter impossible values out of a value list.
// Used by valueOfTok() to find the single "useful" non-impossible value.
static std::list<ValueFlow::Value> removeImpossible(std::list<ValueFlow::Value> values) {
values.remove_if(std::mem_fn(&ValueFlow::Value::isImpossible));
return values;
}
// removeSymbolicTok: filter symbolic and tok values out of a value list.
static std::list<ValueFlow::Value> removeSymbolicTok(std::list<ValueFlow::Value> values) {
values.remove_if([](const ValueFlow::Value& v) {
return v.isSymbolicValue() || v.isTokValue();
});
return values;
}
// tokenValues: returns all ValueFlow::Value objects on the first token
// matched by pattern `tokstr` (via Token::findmatch). This enables
// assertions on operator tokens (e.g. "+", "-") and arbitrary patterns,
// not just on named variables.
#define tokenValues(...) tokenValues_(__FILE__, __LINE__, __VA_ARGS__)
std::list<ValueFlow::Value> tokenValues_(const char* file, int line, const char code[], const char tokstr[], const Settings *s = nullptr) {
SimpleTokenizer tokenizer(s ? *s : settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
const Token *tok = Token::findmatch(tokenizer.tokens(), tokstr);
return tok ? tok->values() : std::list<ValueFlow::Value>();
}
// tokenValues overload: filter by ValueType after fetching.
std::list<ValueFlow::Value> tokenValues_(const char* file, int line, const char code[], const char tokstr[], ValueFlow::Value::ValueType vt) {
std::list<ValueFlow::Value> values = tokenValues_(file, line, code, tokstr);
values.remove_if([vt](const ValueFlow::Value& v) {
return v.valueType != vt;
});
return values;
}
// valueOfTok: returns the single non-impossible, non-tok value on the
// first token matched by `tokstr`, or a default Value() if there is not
// exactly one such value. Mirrors the same helper in testvalueflow.cpp.
#define valueOfTok(...) valueOfTok_(__FILE__, __LINE__, __VA_ARGS__)
ValueFlow::Value valueOfTok_(const char* file, int line, const char code[], const char tokstr[], const Settings *s = nullptr) {
std::list<ValueFlow::Value> values = removeImpossible(tokenValues_(file, line, code, tokstr, s));
values.remove_if([](const ValueFlow::Value& v) { return v.isTokValue(); });
return values.size() == 1U ? values.front() : ValueFlow::Value();
}
// getErrorPathForX: returns the error-path string attached to all values
// on the first "x" token at `linenr`. Format per step: "linenr,msg\n".
// Enables regression testing of diagnostic reasoning chains.
#define getErrorPathForX(...) getErrorPathForX_(__FILE__, __LINE__, __VA_ARGS__)
std::string getErrorPathForX_(const char* file, int line, const char code[], unsigned int linenr) {
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() != "x" || tok->linenr() != linenr)
continue;
std::ostringstream ostr;
for (const ValueFlow::Value &v : tok->values()) {
for (const ErrorPathItem &ep : v.errorPath) {
ostr << ep.first->linenr() << ',' << ep.second << '\n';
}
}
return ostr.str();
}
return "";
}
// __FILE__/__LINE__ delegating macros for value-checking helpers.
// When an assertion fails, the error pinpoints the call site in the test
// body rather than inside the helper implementation.
/// Requirement: x at linenr has a Known integer value equal to `value`.
#define testValueOfXKnown(...) testValueOfXKnown_(__FILE__, __LINE__, __VA_ARGS__)
bool testValueOfXKnown_(const char* file, int line, const char code[], unsigned int linenr, int value) {
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token* tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() != "x" || tok->linenr() != linenr)
continue;
if (std::any_of(tok->values().cbegin(), tok->values().cend(),
[value](const ValueFlow::Value& v) {
return v.isIntValue() && v.isKnown() && v.intvalue == value;
}))
return true;
}
return false;
}
/// Requirement: x at linenr has a Possible integer value equal to `value`.
#define testValueOfXPossible(...) testValueOfXPossible_(__FILE__, __LINE__, __VA_ARGS__)
bool testValueOfXPossible_(const char* file, int line, const char code[], unsigned int linenr, int value) {
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token* tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() != "x" || tok->linenr() != linenr)
continue;
if (std::any_of(tok->values().cbegin(), tok->values().cend(),
[value](const ValueFlow::Value& v) {
return v.isIntValue() && v.isPossible() && v.intvalue == value;
}))
return true;
}
return false;
}
/// Requirement: x at linenr has an Impossible integer value equal to `value`.
#define testValueOfXImpossible(...) testValueOfXImpossible_(__FILE__, __LINE__, __VA_ARGS__)
bool testValueOfXImpossible_(const char* file, int line, const char code[], unsigned int linenr, int value) {
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token* tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() != "x" || tok->linenr() != linenr)
continue;
if (std::any_of(tok->values().cbegin(), tok->values().cend(),
[value](const ValueFlow::Value& v) {
return v.isIntValue() && v.isImpossible() && v.intvalue == value;
}))
return true;
}
return false;
}
/// Requirement: x at linenr has an Inconclusive integer value equal to `value`.
/// Inconclusive differs from Possible: it means the analysis is unsure
/// whether the value is reachable, not just that multiple values exist.
#define testValueOfXInconclusive(...) testValueOfXInconclusive_(__FILE__, __LINE__, __VA_ARGS__)
bool testValueOfXInconclusive_(const char* file, int line, const char code[], unsigned int linenr, int value) {
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token* tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() != "x" || tok->linenr() != linenr)
continue;
if (std::any_of(tok->values().cbegin(), tok->values().cend(),
[value](const ValueFlow::Value& v) {
return v.isIntValue() && v.isInconclusive() && v.intvalue == value;
}))
return true;
}
return false;
}
/// Requirement: x at linenr has a UNINIT value (uninitialized at that point).
/// Phase U: CheckUninitVar reads UNINIT values placed on tokens by the
/// analysis; this helper verifies that annotation is happening.
#define testValueOfXUninit(...) testValueOfXUninit_(__FILE__, __LINE__, __VA_ARGS__)
bool testValueOfXUninit_(const char* file, int line, const char code[], unsigned int linenr) {
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token* tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() != "x" || tok->linenr() != linenr)
continue;
if (std::any_of(tok->values().cbegin(), tok->values().cend(),
[](const ValueFlow::Value& v) {
return v.isUninitValue();
}))
return true;
}
return false;
}
/// Overload: same as above but uses a caller-supplied Settings instance.
/// Needed for FP tests that require a library (e.g. std.cfg) to recognise
/// noreturn functions such as exit().
bool testValueOfXUninit_(const char* file, int line, const char code[],
unsigned int linenr, const Settings& s) {
SimpleTokenizer tokenizer(s, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token* tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() != "x" || tok->linenr() != linenr)
continue;
if (std::any_of(tok->values().cbegin(), tok->values().cend(),
[](const ValueFlow::Value& v) {
return v.isUninitValue();
}))
return true;
}
return false;
}
/// Requirement: the cast token '(' at linenr has a Known integer value
/// equal to `value`. Phase Cast: verifies cast-expression token annotation.
#define testCastKnown(...) testCastKnown_(__FILE__, __LINE__, __VA_ARGS__)
bool testCastKnown_(const char* file, int line, const char code[], unsigned int linenr, int value) {
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token* tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() != "(" || !tok->isCast() || tok->linenr() != linenr)
continue;
if (std::any_of(tok->values().cbegin(), tok->values().cend(),
[value](const ValueFlow::Value& v) {
return v.isIntValue() && v.isKnown() && v.intvalue == value;
}))
return true;
}
return false;
}
/// Requirement: x at linenr has NO integer values at all (neither Known,
/// Possible, nor Impossible).
#define testValueOfXNone(...) testValueOfXNone_(__FILE__, __LINE__, __VA_ARGS__)
bool testValueOfXNone_(const char* file, int line, const char code[], unsigned int linenr) {
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token* tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() != "x" || tok->linenr() != linenr)
continue;
// If any integer value is present, the "none" assertion fails.
if (std::any_of(tok->values().cbegin(), tok->values().cend(),
[](const ValueFlow::Value& v) { return v.isIntValue(); }))
return false;
return true; // found the token, no integer values
}
return true; // token not found — trivially no values
}
// -----------------------------------------------------------------------
// Phase 1 — Forward: basic integer constant tracking
// -----------------------------------------------------------------------
void constantPropagation() {
// Task 1.1: simple assignment from integer literal
// After "int x = 5;" the next use of x should have Known value 5.
{
const char code[] = "void f() {\n" // 1
" int x = 5;\n" // 2
" (void)x;\n" // 3 ← x is 5 (Known)
"}\n";
ASSERT(testValueOfXKnown(code, 3, 5));
}
// Task 1.2a: re-assignment — x has the new value after the second assignment.
{
const char code[] = "void f() {\n" // 1
" int x = 5;\n" // 2
" x = 10;\n" // 3
" (void)x;\n" // 4 ← x is 10 (Known)
"}\n";
ASSERT(testValueOfXKnown(code, 4, 10));
ASSERT(!testValueOfXKnown(code, 4, 5));
}
// Task 1.2b: re-assignment to unknown value — x has no known value.
{
const char code[] = "void f(int y) {\n" // 1
" int x = 5;\n" // 2
" x = y;\n" // 3
" (void)x;\n" // 4 ← no known value
"}\n";
ASSERT(!testValueOfXKnown(code, 4, 5));
}
// Task 1.3: copy propagation — value flows through intermediate variables.
// We test that x on the RHS of "int y = x;" retains the value 5.
{
const char code[] = "void f() {\n" // 1
" int x = 5;\n" // 2
" int y = x;\n" // 3 ← x used here; should be 5
"}\n";
ASSERT(testValueOfXKnown(code, 3, 5));
}
// Task 1.4: non-integer variable — x must NOT receive a known value
// when it is assigned from an untracked type (float cast).
{
const char code[] = "void f(float f) {\n" // 1
" int x = (int)f;\n" // 2
" (void)x;\n" // 3 ← no known value
"}\n";
ASSERT(!testValueOfXKnown(code, 3, 0));
}
}
// -----------------------------------------------------------------------
// Phase 2 — Forward: arithmetic and constant folding
// -----------------------------------------------------------------------
void arithmetic() {
// Task 2.1: arithmetic on two literals.
{
const char code[] = "void f() {\n" // 1
" int x = 3 + 4;\n" // 2
" (void)x;\n" // 3 ← x is 7
"}\n";
ASSERT(testValueOfXKnown(code, 3, 7));
}
{
const char code[] = "void f() {\n" // 1
" int x = 10 - 3;\n" // 2
" (void)x;\n" // 3 ← x is 7
"}\n";
ASSERT(testValueOfXKnown(code, 3, 7));
}
{
const char code[] = "void f() {\n" // 1
" int x = 3 * 4;\n" // 2
" (void)x;\n" // 3 ← x is 12
"}\n";
ASSERT(testValueOfXKnown(code, 3, 12));
}
{
const char code[] = "void f() {\n" // 1
" int x = 10 / 2;\n" // 2
" (void)x;\n" // 3 ← x is 5
"}\n";
ASSERT(testValueOfXKnown(code, 3, 5));
}
// Task 2.2: arithmetic involving a tracked variable.
{
const char code[] = "void f() {\n" // 1
" int x = 5;\n" // 2
" int y = x + 3;\n" // 3 ← x is 5 (Known)
"}\n";
ASSERT(testValueOfXKnown(code, 3, 5));
}
// Task 2.3: compound assignment +=.
{
const char code[] = "void f() {\n" // 1
" int x = 5;\n" // 2
" x += 3;\n" // 3
" (void)x;\n" // 4 ← x is 8
"}\n";
ASSERT(testValueOfXKnown(code, 4, 8));
}
// Task 2.3: compound assignment -=.
{
const char code[] = "void f() {\n" // 1
" int x = 10;\n" // 2
" x -= 3;\n" // 3
" (void)x;\n" // 4 ← x is 7
"}\n";
ASSERT(testValueOfXKnown(code, 4, 7));
}
// Task 2.4: post-increment.
{
const char code[] = "void f() {\n" // 1
" int x = 5;\n" // 2
" x++;\n" // 3
" (void)x;\n" // 4 ← x is 6
"}\n";
ASSERT(testValueOfXKnown(code, 4, 6));
}
// Task 2.4: pre-decrement.
{
const char code[] = "void f() {\n" // 1
" int x = 5;\n" // 2
" --x;\n" // 3
" (void)x;\n" // 4 ← x is 4
"}\n";
ASSERT(testValueOfXKnown(code, 4, 4));
}
// Task 2.5: division by zero — no crash, no value assigned.
{
const char code[] = "void f() {\n" // 1
" int x = 10 / 0;\n" // 2
" (void)x;\n" // 3 ← no known value
"}\n";
ASSERT(!testValueOfXKnown(code, 3, 0));
}
}
// -----------------------------------------------------------------------
// Phase 3 — Forward: branches (if/else)
// -----------------------------------------------------------------------
void forwardBranches() {
// Task 3.1: both branches assign the same value → Known after merge.
{
const char code[] = "void f(int c) {\n" // 1
" int x;\n" // 2
" if (c) { x = 1; } else { x = 1; }\n" // 3
" (void)x;\n" // 4 ← x is 1 (Known)
"}\n";
ASSERT(testValueOfXKnown(code, 4, 1));
}
// Task 3.2: branches assign DIFFERENT values → two Possible values.
// The analysis must NOT report a single Known value after the merge.
// Both Possible values must be present.
{
const char code[] = "void f(int c) {\n" // 1
" int x;\n" // 2
" if (c) { x = 1; } else { x = 2; }\n" // 3
" (void)x;\n" // 4
"}\n";
ASSERT(testValueOfXPossible(code, 4, 1));
ASSERT(testValueOfXPossible(code, 4, 2));
ASSERT(!testValueOfXKnown(code, 4, 1));
ASSERT(!testValueOfXKnown(code, 4, 2));
}
// Task 3.3: one-sided if (no else) → both the original and the
// branch-modified values are Possible after the if.
{
const char code[] = "void f(int c) {\n" // 1
" int x = 5;\n" // 2
" if (c) { x = 10; }\n" // 3
" (void)x;\n" // 4
"}\n";
ASSERT(testValueOfXPossible(code, 4, 5));
ASSERT(testValueOfXPossible(code, 4, 10));
}
// Task 3.4: if with return in the then-branch → the surviving path
// (no-return) continues with x=10 as a Known value.
{
const char code[] = "void f(int c) {\n" // 1
" int x = 5;\n" // 2
" if (c) { return; }\n" // 3
" x = 10;\n" // 4
" (void)x;\n" // 5 ← x is 10 (Known)
"}\n";
ASSERT(testValueOfXKnown(code, 5, 10));
}
// Task 3.5: condition constraint inside the then-block.
// After "if (x == 5)" the variable x is Known 5 inside the block.
{
const char code[] = "void f(int x) {\n" // 1
" if (x == 5) {\n" // 2
" (void)x;\n" // 3 ← x is 5 (Known) inside block
" }\n" // 4
"}\n";
ASSERT(testValueOfXKnown(code, 3, 5));
}
}
// -----------------------------------------------------------------------
// Phase 4 — Forward: loops
// -----------------------------------------------------------------------
void forwardLoops() {
// Task 4.1: variable modified in loop body → unknown after the loop.
// After a while loop that increments x, x cannot be known.
{
const char code[] = "void f(int c) {\n" // 1
" int x = 5;\n" // 2
" while (c) { x++; }\n" // 3
" (void)x;\n" // 4 ← x is NOT known
"}\n";
ASSERT(!testValueOfXKnown(code, 4, 5));
ASSERT(!testValueOfXKnown(code, 4, 6));
}
// Task 4.2: loop-invariant variable survives the loop with Known value.
{
const char code[] = "void f(int n) {\n" // 1
" int x = 5;\n" // 2
" for (int i = 0; i < n; i++) {}\n" // 3
" (void)x;\n" // 4 ← x is still 5
"}\n";
ASSERT(testValueOfXKnown(code, 4, 5));
}
// Task NW1: while loop with null-guard && condition.
// After "while (x && x->n > 0)", x might be null at the loop exit
// (the loop can exit because x became null OR because x->n <= 0).
// Requirement: x must carry a Possible null (0) value at line 6.
{
const char code[] = "struct S { int n; struct S *next; };\n" // 1
"int foo(struct S *x) {\n" // 2
" while (x && x->n > 0) {\n" // 3
" x = x->next;\n" // 4
" }\n" // 5
" (void)x;\n" // 6
"}\n";
ASSERT(testValueOfXPossible(code, 6, 0));
}
// Task NW2: simple while (x) → after the loop, x is Known null.
// Requirement: x must carry a Known null (0) value at line 6.
{
const char code[] = "struct S { struct S *next; };\n" // 1
"void foo(struct S *x) {\n" // 2
" while (x) {\n" // 3
" x = x->next;\n" // 4
" }\n" // 5
" (void)x;\n" // 6
"}\n";
ASSERT(testValueOfXKnown(code, 6, 0));
}
// Task NW3: do-while loop with null-guard && condition.
// After "do { x = x->next; } while (x && x->n > 0)", the loop exits
// when the condition is false — which happens when x is null.
// Requirement: x must carry a Possible null (0) value after the loop.
{
const char code[] = "struct S { int n; struct S* next; };\n" // 1
"int foo(struct S* x) {\n" // 2
" do {\n" // 3
" x = x->next;\n" // 4
" } while (x && x->n > 0);\n" // 5
" (void)x;\n" // 6
"}\n";
ASSERT(testValueOfXPossible(code, 6, 0));
}
}
// -----------------------------------------------------------------------
// Phase 5 — Forward: function calls (conservative)
// -----------------------------------------------------------------------
void forwardFunctionCalls() {
// Task 5.1: local scalar variables survive a function call.
// x is a local int; foo() has no parameters and cannot access x,
// so x remains known as 5 after the call.
{
const char code[] = "void foo();\n" // 1
"void f() {\n" // 2
" int x = 5;\n" // 3
" foo();\n" // 4
" (void)x;\n" // 5 ← x is still 5 (local scalar)
"}\n";
ASSERT(testValueOfXKnown(code, 5, 5));
}
// Task 5.2: variables assigned AFTER a call are still tracked.
{
const char code[] = "void foo();\n" // 1
"void f() {\n" // 2
" foo();\n" // 3
" int x = 5;\n" // 4
" (void)x;\n" // 5 ← x is 5 (Known)
"}\n";
ASSERT(testValueOfXKnown(code, 5, 5));
}
}
// -----------------------------------------------------------------------
// Phase B1 — Backward: basic constraint propagation
// -----------------------------------------------------------------------
void backwardConstraints() {
// Task B1.1: condition "if (x == 5)" propagates x's value backward
// to uses of x that appear BEFORE the condition.
{
const char code[] = "void f(int x) {\n" // 1
" (void)x;\n" // 2 ← backward: x is possibly 5
" if (x == 5) {}\n" // 3
"}\n";
ASSERT(testValueOfXPossible(code, 2, 5));
}
// Task B1.2: "if (x != 0)" propagates the impossible value 0 backward.
{
const char code[] = "void f(int x) {\n" // 1
" (void)x;\n" // 2 ← backward: x is impossible 0
" if (x != 0) {}\n" // 3
"}\n";
ASSERT(testValueOfXImpossible(code, 2, 0));
}
// Task B1.3: an assignment to x BETWEEN the use and the condition
// severs the backward chain — x at line 2 must NOT get the constraint.
{
const char code[] = "void f(int x) {\n" // 1
" (void)x;\n" // 2 ← must NOT have value 5
" x = 10;\n" // 3 severs backward chain
" if (x == 5) {}\n" // 4
"}\n";
ASSERT(!testValueOfXPossible(code, 2, 5));
}
// Task B1.4: constraint propagates to multiple uses before the condition.
{
const char code[] = "void g(int);\n" // 1
"void f(int x) {\n" // 2
" g(x);\n" // 3 ← backward: x possibly 5
" (void)x;\n" // 4 ← backward: x possibly 5
" if (x == 5) {}\n" // 5
"}\n";
ASSERT(testValueOfXPossible(code, 4, 5));
}
}
// -----------------------------------------------------------------------
// Phase R — Relational operator constraints (< > <= >=)
// -----------------------------------------------------------------------
//
// When a condition uses a relational operator, the analysis constrains x
// inside the true branch. For "if (x > 5)" the minimum value of x in
// the then-block is 6; for "if (x < 5)" the maximum is 4. These
// constraints are expressed as Possible values at the boundary.
//
// Requirement: false negatives are preferable to false positives — if the
// analysis cannot determine the exact constraint it must not emit a wrong
// Known value.
void relationalConstraints() {
// R1: "if (x > 5)" → inside the block x is possibly 6 (the minimum
// value that satisfies x > 5 for integers).
{
const char code[] = "void f(int x) {\n" // 1
" if (x > 5) {\n" // 2
" (void)x;\n" // 3 ← x possibly 6
" }\n" // 4
"}\n";
TODO_ASSERT_EQUALS(true, false, testValueOfXPossible(code, 3, 6));
}
// R2: "if (x < 5)" → inside the block x is possibly 4 (the maximum
// value that satisfies x < 5 for integers).
{
const char code[] = "void f(int x) {\n" // 1
" if (x < 5) {\n" // 2
" (void)x;\n" // 3 ← x possibly 4
" }\n" // 4
"}\n";
TODO_ASSERT_EQUALS(true, false, testValueOfXPossible(code, 3, 4));
}
// R3: "if (x >= 5)" → x is possibly 5 inside the block (exact lower bound).
{
const char code[] = "void f(int x) {\n" // 1
" if (x >= 5) {\n" // 2
" (void)x;\n" // 3 ← x possibly 5
" }\n" // 4
"}\n";
TODO_ASSERT_EQUALS(true, false, testValueOfXPossible(code, 3, 5));
}
// R4: "if (x <= 5)" → x is possibly 5 inside the block (exact upper bound).
{
const char code[] = "void f(int x) {\n" // 1
" if (x <= 5) {\n" // 2
" (void)x;\n" // 3 ← x possibly 5
" }\n" // 4
"}\n";
TODO_ASSERT_EQUALS(true, false, testValueOfXPossible(code, 3, 5));
}
// R5: reversed operands "if (5 < x)" is equivalent to "if (x > 5)".
{
const char code[] = "void f(int x) {\n" // 1
" if (5 < x) {\n" // 2
" (void)x;\n" // 3 ← x possibly 6
" }\n" // 4
"}\n";
TODO_ASSERT_EQUALS(true, false, testValueOfXPossible(code, 3, 6));
}
// R6: relational constraint does NOT produce a Known value — the
// analysis must not infer x == 6 just because x > 5.
{
const char code[] = "void f(int x) {\n" // 1
" if (x > 5) {\n" // 2
" (void)x;\n" // 3 ← x must NOT be Known 6
" }\n" // 4
"}\n";
ASSERT(!testValueOfXKnown(code, 3, 6));
}
// R7: backward propagation of relational constraint.
// Before "if (x > 5)" the variable x possibly satisfies x > 5.
{
const char code[] = "void f(int x) {\n" // 1
" (void)x;\n" // 2 ← backward: x possibly 6
" if (x > 5) {}\n" // 3
"}\n";
TODO_ASSERT_EQUALS(true, false, testValueOfXPossible(code, 2, 6));
}
}
// -----------------------------------------------------------------------
// Phase OT — Operator token value annotation
// -----------------------------------------------------------------------
//
// Checkers such as checkZeroDivision and arrayIndex examine the value on
// the *operator token* itself (e.g. the "/" token) to decide whether a
// division by zero is happening. DataFlow must annotate operator tokens
// with the computed value when both operands are known constants, not
// only the receiving variable.
//
// These tests use valueOfTok() which returns the single non-impossible,
// non-tok value on the first token matching a pattern — mirroring how
// testvalueflow.cpp tests arithmetic operator annotation.
void operatorTokenValues() {
// OT1: "3 + 4" — the "+" token must carry value 7.
{
const char code[] = "void f() { int x = 3 + 4; }";
TODO_ASSERT_EQUALS(7, 0, valueOfTok(code, "+").intvalue);
}
// OT2: "10 - 3" — the "-" token must carry value 7.
{
const char code[] = "void f() { int x = 10 - 3; }";
TODO_ASSERT_EQUALS(7, 0, valueOfTok(code, "-").intvalue);
}
// OT3: "3 * 4" — the "*" token must carry value 12.
{
const char code[] = "void f() { int x = 3 * 4; }";
TODO_ASSERT_EQUALS(12, 0, valueOfTok(code, "*").intvalue);
}
// OT4: "10 / 2" — the "/" token must carry value 5.
{
const char code[] = "void f() { int x = 10 / 2; }";
TODO_ASSERT_EQUALS(5, 0, valueOfTok(code, "/").intvalue);
}
// OT5: literal integer token must carry its own Known value.
// tokenValues() on "42" must include a Known 42.
// (This is already tested by literalAnnotation; here we confirm
// the new tokenValues() primitive returns the right result.)
{
const char code[] = "void f() { return 42; }";
const auto vals = tokenValues(code, "42");
ASSERT(std::any_of(vals.begin(), vals.end(), [](const ValueFlow::Value& v) {
return v.isIntValue() && v.isKnown() && v.intvalue == 42;
}));
}
// OT6: zero literal in divisor position must carry Known 0 via tokenValues().
// This mirrors the literalAnnotation test but exercises the new helper.
{
const char code[] = "int f(int x) { return x / 0; }";
const auto vals = tokenValues(code, "0");
ASSERT(std::any_of(vals.begin(), vals.end(), [](const ValueFlow::Value& v) {
return v.isIntValue() && v.isKnown() && v.intvalue == 0;
}));
}
}
// -----------------------------------------------------------------------
// Phase UI — Unsigned integer impossible-value constraints
// -----------------------------------------------------------------------
//
// An unsigned integer type (uint8_t, uint16_t, uint32_t, unsigned int)
// can never hold a negative value. ValueFlow annotates such variables
// with an Impossible(-1) value (representing "< 0 is impossible") so
// that checkers can suppress spurious "x < 0 is always false" checks.
//
// Requirement: false negatives are preferable — if DataFlow cannot
// determine the type is unsigned it must not emit an incorrect constraint.
void unsignedImpossible() {
// UI1: uint32_t variable has Impossible(-1) — it can never be negative.
{
const char code[] = "#include <cstdint>\n" // 1
"void f(uint32_t x) {\n" // 2
" (void)x;\n" // 3 ← x is Impossible(-1)
"}\n";
TODO_ASSERT_EQUALS(true, false, testValueOfXImpossible(code, 3, -1));
}
// UI2: signed int does NOT get the Impossible(-1) constraint.
{
const char code[] = "void f(int x) {\n" // 1
" (void)x;\n" // 2 ← no Impossible(-1)
"}\n";
ASSERT(!testValueOfXImpossible(code, 2, -1));
}
// UI3: unsigned int parameter also has Impossible(-1).
{
const char code[] = "void f(unsigned int x) {\n" // 1
" (void)x;\n" // 2 ← x is Impossible(-1)
"}\n";
TODO_ASSERT_EQUALS(true, false, testValueOfXImpossible(code, 2, -1));
}
}
// -----------------------------------------------------------------------
// Phase SW — Switch/case value propagation
// -----------------------------------------------------------------------
//
// Inside a switch case block, the switched variable is Known equal to the
// case label value. This is the same constraint that ValueFlow's
// valueFlowSwitchVariable applies.
//
// Requirement: the value is only Known inside the case block, not after
// the switch statement completes (where multiple cases may have executed).
void switchVariable() {
// SW1: inside "case 5:" the switched variable x is Known 5.
{
const char code[] = "void f(int x) {\n" // 1
" switch (x) {\n" // 2
" case 5:\n" // 3
" (void)x;\n" // 4 ← x is Known (or Possible) 5
" break;\n" // 5
" }\n" // 6
"}\n";
TODO_ASSERT_EQUALS(true, false, testValueOfXKnown(code, 4, 5));
}
// SW2: after the switch, x must NOT be Known 5 (other cases exist).
{
const char code[] = "void f(int x) {\n" // 1
" switch (x) {\n" // 2
" case 5: break;\n" // 3
" case 10: break;\n" // 4
" }\n" // 5
" (void)x;\n" // 6 ← x is NOT Known 5
"}\n";
ASSERT(!testValueOfXKnown(code, 6, 5));
}
// SW3: default case does not constrain x to a specific value.
{
const char code[] = "void f(int x) {\n" // 1
" switch (x) {\n" // 2
" default:\n" // 3
" (void)x;\n" // 4 ← x has no specific Known value
" break;\n" // 5
" }\n" // 6
"}\n";
ASSERT(!testValueOfXKnown(code, 4, 0));
}
}
// -----------------------------------------------------------------------
// Phase LB — For-loop variable bounds inside the loop body
// -----------------------------------------------------------------------
//
// For a simple counted loop "for (int x = 0; x < N; x++)" the analysis
// should recognize that inside the body x is in [0, N-1]. ValueFlow's
// valueFlowForLoop emits both the minimum (0) and the maximum (N-1) as
// Possible values on the loop variable token inside the body.
//
// Requirement: if N is a compile-time constant the bounds are exact; if N
// is unknown the analysis must not emit a false Known value.
void loopBounds() {
// LB1: loop variable x ranges over [0, 9] — both bounds are Possible
// inside the body when the limit is a known literal.
{
const char code[] = "void f() {\n" // 1
" for (int x = 0; x < 10; x++) {\n" // 2
" (void)x;\n" // 3 ← x possibly 0 and 9
" }\n" // 4
"}\n";
TODO_ASSERT_EQUALS(true, false, testValueOfXPossible(code, 3, 0));
TODO_ASSERT_EQUALS(true, false, testValueOfXPossible(code, 3, 9));
}
// LB2: loop variable must NOT be Known 0 after the loop — it has
// exited with value 10 (post-condition of the for loop).
{
const char code[] = "void f() {\n" // 1
" for (int x = 0; x < 10; x++) {}\n" // 2
" (void)x;\n" // 3 ← x is NOT Known 0
"}\n";
ASSERT(!testValueOfXKnown(code, 3, 0));
}
// LB3: loop with unknown limit — x must not be given a Known bound.
{
const char code[] = "void f(int n) {\n" // 1
" for (int x = 0; x < n; x++) {\n" // 2
" (void)x;\n" // 3 ← x must NOT be Known 0
" }\n" // 4
"}\n";