Skip to content

Commit bd33cf5

Browse files
authored
Fix #11389 Do not warn for truncLongCastReturn if operands have known valid int (danmar#8192)
This fix handles the first example in ticket, i.e. when the value is known to be a valid int: long f() { int n = 1; return n << 12; }
1 parent 5f6aebe commit bd33cf5

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

lib/checktype.cpp

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -383,8 +383,12 @@ void CheckType::checkLongCast()
383383
const ValueType *type = tok->astOperand1()->valueType();
384384
if (type && checkTypeCombination(*type, *retVt, *mSettings) &&
385385
type->pointer == 0U &&
386-
type->originalTypeName.empty())
387-
ret = tok;
386+
type->originalTypeName.empty()) {
387+
if (!tok->astOperand1()->hasKnownIntValue()) {
388+
ret = tok;
389+
} else if (!mSettings->platform.isIntValue(tok->astOperand1()->getKnownIntValue()))
390+
ret = tok;
391+
}
388392
}
389393
// All return statements must have problem otherwise no warning
390394
if (ret != tok) {

test/testtype.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -465,6 +465,26 @@ class TestType : public TestFixture {
465465
check(code2, dinit(CheckOptions, $.settings = &settingsWin));
466466
ASSERT_EQUALS("[test.cpp:2:3]: (style) int result is returned as long long value. If the return value is long long to avoid loss of information, then you have loss of information. [truncLongCastReturn]\n", errout_str());
467467

468+
const char code3[] = "long f() {\n"
469+
" int n = 1;\n"
470+
" return n << 12;\n"
471+
"}\n";
472+
check(code3, dinit(CheckOptions, $.settings = &settings));
473+
ASSERT_EQUALS("", errout_str());
474+
475+
const char code4[] = "long f(int n) {\n"
476+
" return n << 12;\n"
477+
"}\n";
478+
check(code4, dinit(CheckOptions, $.settings = &settings));
479+
ASSERT_EQUALS("[test.cpp:2:5]: (style) int result is returned as long value. If the return value is long to avoid loss of information, then you have loss of information. [truncLongCastReturn]\n", errout_str());
480+
481+
const char code5[] = "long f() {\n"
482+
" unsigned int n = 1U << 20;\n"
483+
" return n << 20;\n"
484+
"}\n";
485+
check(code5, dinit(CheckOptions, $.settings = &settings));
486+
ASSERT_EQUALS("[test.cpp:3:5]: (style) int result is returned as long value. If the return value is long to avoid loss of information, then you have loss of information. [truncLongCastReturn]\n", errout_str());
487+
468488
// typedef
469489
check("size_t f(int x, int y) {\n"
470490
" return x * y;\n"

0 commit comments

Comments
 (0)