From 47b98470eb983227184cc61cdebd1d759b47278a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Tue, 19 Nov 2013 18:07:12 +0100 Subject: [PATCH] Tokenizer: Simplify float casts of integer constants --- lib/tokenize.cpp | 14 ++++++++++++++ lib/tokenize.h | 5 +++++ test/testtokenize.cpp | 8 ++++++++ 3 files changed, 27 insertions(+) diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp index 6ce67b1ac..0aa08544e 100644 --- a/lib/tokenize.cpp +++ b/lib/tokenize.cpp @@ -1994,6 +1994,9 @@ bool Tokenizer::tokenize(std::istream &code, simplifyVariableMultipleAssign(); + // Simplify float casts (float)1 => 1.0 + simplifyFloatCasts(); + // Remove redundant parentheses simplifyRedundantParentheses(); for (Token *tok = list.front(); tok; tok = tok->next()) @@ -4789,6 +4792,17 @@ void Tokenizer::simplifyUndefinedSizeArray() } } +void Tokenizer::simplifyFloatCasts() +{ + for (Token *tok = list.front(); tok; tok = tok->next()) { + if (Token::Match(tok->next(), "( float|double ) %num%") && MathLib::isInt(tok->strAt(4))) { + tok->deleteNext(3); + tok = tok->next(); + tok->str(tok->str() + ".0"); + } + } +} + void Tokenizer::simplifyCasts() { for (Token *tok = list.front(); tok; tok = tok->next()) { diff --git a/lib/tokenize.h b/lib/tokenize.h index a98bc8e1b..295d8ac06 100644 --- a/lib/tokenize.h +++ b/lib/tokenize.h @@ -325,6 +325,11 @@ public: */ void simplifyTypedef(); + /** + * Simplify float casts (float)1 => 1.0 + */ + void simplifyFloatCasts(); + /** * Simplify casts */ diff --git a/test/testtokenize.cpp b/test/testtokenize.cpp index 87f84ad2d..3ff340586 100644 --- a/test/testtokenize.cpp +++ b/test/testtokenize.cpp @@ -97,6 +97,8 @@ private: TEST_CASE(removeCast12); TEST_CASE(removeCast13); + TEST_CASE(simplifyFloatCasts); // float casting a integer + TEST_CASE(inlineasm); TEST_CASE(ifAddBraces1); @@ -1123,6 +1125,12 @@ private: tokenizeAndStringify("; float angle = (float) +tilt;", true)); } + void simplifyFloatCasts() { // float casting integers + ASSERT_EQUALS("a = 1.0 ;", tokenizeAndStringify("a = (float)1;")); + ASSERT_EQUALS("a = 1.0 ;", tokenizeAndStringify("a = ((float)1);")); + ASSERT_EQUALS("a = 291.0 ;", tokenizeAndStringify("a = ((float)0x123);")); + } + void inlineasm() { ASSERT_EQUALS("asm ( \"mov ax , bx\" ) ;", tokenizeAndStringify("asm { mov ax,bx };")); ASSERT_EQUALS("asm ( \"mov ax , bx\" ) ;", tokenizeAndStringify("_asm { mov ax,bx };"));