From a9d56f2738e1b7dd9c4bfdd4ec2ff7a0a8a5e193 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Mon, 12 Mar 2012 17:32:30 +0100 Subject: [PATCH] Tokenizer: simplify known variable value inside conditional block --- lib/tokenize.cpp | 16 ++++++++++++++++ test/testtokenize.cpp | 15 +++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp index 1f7fa463e..c52c0d514 100644 --- a/lib/tokenize.cpp +++ b/lib/tokenize.cpp @@ -6115,6 +6115,22 @@ bool Tokenizer::simplifyKnownVariables() ret |= simplifyKnownVariablesSimplify(&tok2, tok3, varid, structname, value, valueVarId, valueIsPointer, valueToken, indentlevel); } + else if (Token::Match(tok2, "( %var% == %num% ) {")) { + const unsigned int varid = tok2->next()->varId(); + if (varid == 0) + continue; + + const std::string structname = ""; + + const Token *valueToken = tok2->tokAt(3); + std::string value(tok2->strAt(3)); + const unsigned int valueVarId = 0; + const bool valueIsPointer = false; + + Token *scopeStart = tok2->tokAt(6); + ret |= simplifyKnownVariablesSimplify(&scopeStart, scopeStart, varid, structname, value, valueIsPointer, valueVarId, valueToken, 0); + } + else if (Token::Match(tok2, "strcpy ( %var% , %str% ) ;")) { const unsigned int varid(tok2->tokAt(2)->varId()); if (varid == 0) diff --git a/test/testtokenize.cpp b/test/testtokenize.cpp index 24f89aa91..35c15c7d5 100644 --- a/test/testtokenize.cpp +++ b/test/testtokenize.cpp @@ -149,6 +149,7 @@ private: TEST_CASE(simplifyKnownVariables44); // ticket #3117 - don't simplify static variables TEST_CASE(simplifyKnownVariables45); // ticket #3281 - static constant variable not simplified TEST_CASE(simplifyKnownVariables46); // ticket #3587 - >> + TEST_CASE(simplifyKnownVariablesIfEq); // if (a==5) => a is 5 in the block TEST_CASE(simplifyKnownVariablesBailOutAssign1); TEST_CASE(simplifyKnownVariablesBailOutAssign2); TEST_CASE(simplifyKnownVariablesBailOutFor1); @@ -2306,6 +2307,20 @@ private: } } + void simplifyKnownVariablesIfEq() { + const char code[] = "void f(int x) {\n" + " if (x==5) {\n" + " return x;\n" + " }\n" + "}"; + const char expected[] = "void f ( int x ) {\n" + "if ( x == 5 ) {\n" + "return 5 ;\n" + "}\n" + "}"; + ASSERT_EQUALS(expected, tokenizeAndStringify(code, true, true, Settings::Unspecified, "test.c")); + } + void simplifyKnownVariablesBailOutAssign1() { const char code[] = "int foo() {\n" " int i; i = 0;\n"