diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp index 1f1d1ca9e..221adf499 100644 --- a/lib/tokenize.cpp +++ b/lib/tokenize.cpp @@ -4591,6 +4591,18 @@ void Tokenizer::simplifyCasts() tok = tok->linkAt(2); continue; } + // #4164 : ((unsigned char)1) => (1) + if (Token::Match(tok->next(), "( unsigned| %type% ) %num%") && tok->next()->link()->previous()->isStandardType()) { + const MathLib::bigint value = MathLib::toLongNumber(tok->next()->link()->next()->str()); + unsigned int bits = 8 * _typeSize[tok->next()->link()->previous()->str()]; + if (!tok->tokAt(2)->isUnsigned()) + bits--; + if (bits < 31 && value >= 0 && value < (1 << bits)) { + Token::eraseTokens(tok, tok->next()->link()->next()); + } + continue; + } + while ((Token::Match(tok->next(), "( %type% *| *| *| ) *|&| %var%") && (tok->str() != ")" || tok->tokAt(2)->isStandardType())) || Token::Match(tok->next(), "( %type% %type% *| *| *| ) *|&| %var%") || (!tok->isName() && (Token::Match(tok->next(), "( %type% * *| *| ) (") || diff --git a/test/testsimplifytokens.cpp b/test/testsimplifytokens.cpp index 7b8483e2e..4b7ea0285 100644 --- a/test/testsimplifytokens.cpp +++ b/test/testsimplifytokens.cpp @@ -509,6 +509,10 @@ private: // no simplification as the cast may be important here. see #2897 for example ASSERT_EQUALS("; * ( ( char * ) p + 1 ) = 0 ;", tok("; *((char *)p + 1) = 0;")); + + ASSERT_EQUALS("if ( true )", tok("if ((unsigned char)1)")); // #4164 + ASSERT_EQUALS("f ( 200 )", tok("f((unsigned char)200)")); + ASSERT_EQUALS("f ( ( char ) 1234 )", tok("f((char)1234)")); // dont simplify downcast }