From 2e61201c18cf81c3a4e3910111b938fe6c415593 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Sun, 17 May 2009 18:58:32 +0200 Subject: [PATCH] STL: It is ok to compare vector iterators with < https://apps.sourceforge.net/trac/cppcheck/ticket/313 --- src/checkstl.cpp | 40 ++++++++++++++++++++++++++++------------ test/teststl.cpp | 11 ++++++++++- 2 files changed, 38 insertions(+), 13 deletions(-) diff --git a/src/checkstl.cpp b/src/checkstl.cpp index b2ede2f56..4a77ef9e8 100644 --- a/src/checkstl.cpp +++ b/src/checkstl.cpp @@ -335,24 +335,40 @@ void CheckStl::stlBoundries() { for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if (Token::Match(tok, "for (")) + // Declaring iterator.. + if (Token::Match(tok, "list <")) { - for (const Token *tok2 = tok->tokAt(2); tok2 && tok2->str() != ";"; tok2 = tok2->next()) + while (tok && tok->str() != ">") + tok = tok->next(); + if (!tok) + break; + + if (Token::Match(tok, "> :: iterator|const_iterator %var% =|;")) { - if (Token::Match(tok2, "%var% = %var% . begin ( ) ; %var% < %var% . end ( ) ") && - tok2->str() == tok2->tokAt(8)->str() && - tok2->tokAt(2)->str() == tok2->tokAt(10)->str()) + const unsigned int iteratorid(tok->tokAt(3)->varId()); + if (iteratorid == 0) + continue; + + // Using "iterator < ..." is not allowed + unsigned int indentlevel = 0; + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { - stlBoundriesError(tok2); - break; + if (tok2->str() == "{") + ++indentlevel; + else if (tok2->str() == "}") + { + if (indentlevel == 0) + break; + --indentlevel; + } + else if (tok2->varId() == iteratorid && tok2->next() && tok2->next()->str() == "<") + { + stlBoundriesError(tok2); + break; + } } } } - - if (Token::Match(tok, "while ( %var% < %var% . end ( )")) - { - stlBoundriesError(tok); - } } } diff --git a/test/teststl.cpp b/test/teststl.cpp index 9f99208b8..8bb99cc6a 100644 --- a/test/teststl.cpp +++ b/test/teststl.cpp @@ -377,10 +377,19 @@ private: { check("void f()\n" "{\n" + " std::list::iterator it;\n" " for (it = ab.begin(); it < ab.end(); ++it)\n" " ;\n" "}\n"); - ASSERT_EQUALS("[test.cpp:3]: (error) STL range check should be using != and not < since the order of the pointers isn't guaranteed\n", errout.str()); + ASSERT_EQUALS("[test.cpp:4]: (error) STL range check should be using != and not < since the order of the pointers isn't guaranteed\n", errout.str()); + + check("void f()\n" + "{\n" + " std::vector::iterator it;\n" + " for (it = ab.begin(); it < ab.end(); ++it)\n" + " ;\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); } };