From 17e776861e331c0238a77a66009cf975323240d9 Mon Sep 17 00:00:00 2001 From: chrchr-github <78114321+chrchr-github@users.noreply.github.com> Date: Tue, 28 Feb 2023 15:05:45 +0100 Subject: [PATCH] Get type from auto with index operator (#4826) --- lib/token.cpp | 6 ++++++ test/testfunctions.cpp | 12 ++++++++++++ test/testsymboldatabase.cpp | 14 ++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/lib/token.cpp b/lib/token.cpp index d2fe45e4a..f4881ad59 100644 --- a/lib/token.cpp +++ b/lib/token.cpp @@ -2265,6 +2265,12 @@ std::pair Token::typeDecl(const Token* tok, bool poi if (Token::simpleMatch(tok2, "=") && Token::Match(tok2->astOperand2(), "!!=") && tok != tok2->astOperand2()) { tok2 = tok2->astOperand2(); + if (Token::simpleMatch(tok2, "[") && tok2->astOperand1()) { + const ValueType* vt = tok2->astOperand1()->valueType(); + if (vt && vt->containerTypeToken) + return { vt->containerTypeToken, vt->containerTypeToken->linkAt(-1) }; + } + const Token* varTok = tok2; // try to find a variable if (Token::Match(varTok, ":: %name%")) varTok = varTok->next(); diff --git a/test/testfunctions.cpp b/test/testfunctions.cpp index ba9b628fa..9cccc61fd 100644 --- a/test/testfunctions.cpp +++ b/test/testfunctions.cpp @@ -1986,6 +1986,18 @@ private: "}\n"); ASSERT_EQUALS("", errout.str()); + check("void f(std::vector>>& v, int i, int j) {\n" + " auto& s = v[i][j];\n" + " s.insert(0);\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + + check("int f(const std::vector& v, int i, char c) {\n" + " const auto& s = v[i];\n" + " return s.find(c);\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + settings = settings_old; } diff --git a/test/testsymboldatabase.cpp b/test/testsymboldatabase.cpp index 72d5aa75c..805a587bd 100644 --- a/test/testsymboldatabase.cpp +++ b/test/testsymboldatabase.cpp @@ -481,6 +481,7 @@ private: TEST_CASE(valueType1); TEST_CASE(valueType2); + TEST_CASE(valueType3); TEST_CASE(valueTypeThis); TEST_CASE(variadic1); // #7453 @@ -8109,6 +8110,19 @@ private: } } + void valueType3() { + GET_SYMBOL_DB("void f(std::vector>>& v, int i, int j) {\n" + " auto& s = v[i][j];\n" + " s.insert(0);\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + + const Token* tok = tokenizer.tokens(); + tok = Token::findsimplematch(tok, "s ."); + ASSERT(tok && tok->valueType()); + ASSERT_EQUALS("container(std :: set|unordered_set <)", tok->valueType()->str()); + } + void valueTypeThis() { ASSERT_EQUALS("C *", typeOf("class C { C() { *this = 0; } };", "this")); ASSERT_EQUALS("const C *", typeOf("class C { void foo() const; }; void C::foo() const { *this = 0; }", "this"));