Skip to content

Commit 5a8d096

Browse files
authored
[clang-tidy] Fix false positive for cppcoreguidelines-pro-bounds-pointer-arithmetic (#127394)
this PR fixes #126424 for `ArraySubScriptExpr`, `hasBase` Matcher will get right operand when it is not integer type, but is not for sure that left operand is integer type. For the example code below `hasBase` will get `r` for the Subsequent matching and causing false positive. ``` template <typename R> int f(std::map<R*, int>& map, R* r) { return map[r]; } ``` so is needed to see if index is integer type to avoid this situation.
1 parent cbfd0d6 commit 5a8d096

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsPointerArithmeticCheck.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ void ProBoundsPointerArithmeticCheck::registerMatchers(MatchFinder *Finder) {
4242
arraySubscriptExpr(
4343
hasBase(ignoringImpCasts(
4444
anyOf(AllPointerTypes,
45-
hasType(decayedType(hasDecayedType(pointerType())))))))
45+
hasType(decayedType(hasDecayedType(pointerType())))))),
46+
hasIndex(hasType(isInteger())))
4647
.bind("expr"),
4748
this);
4849
}

clang-tools-extra/docs/ReleaseNotes.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,11 @@ Changes in existing checks
216216
<clang-tidy/checks/cppcoreguidelines/missing-std-forward>` check by adding a
217217
flag to specify the function used for forwarding instead of ``std::forward``.
218218

219+
- Improved :doc:`cppcoreguidelines-pro-bounds-pointer-arithmetic
220+
<clang-tidy/checks/cppcoreguidelines/pro-bounds-pointer-arithmetic>` check by
221+
fixing false positives when calling indexing operators that do not perform
222+
pointer arithmetic in template, for example ``std::map::operator[]``.
223+
219224
- Improved :doc:`cppcoreguidelines-rvalue-reference-param-not-moved
220225
<clang-tidy/checks/cppcoreguidelines/rvalue-reference-param-not-moved>` check
221226
by adding a flag to specify the function used for moving instead of

clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-pointer-arithmetic.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,3 +87,25 @@ void okay() {
8787

8888
for(int ii : a) ; // OK, pointer arithmetic generated by compiler
8989
}
90+
91+
namespace gh126424 {
92+
93+
namespace std {
94+
template <typename, typename>
95+
class pair {};
96+
97+
template <typename Key, typename Value>
98+
class map {
99+
public:
100+
using value_type = pair<Key, Value>;
101+
value_type& operator[](const Key& key);
102+
value_type& operator[](Key&& key);
103+
};
104+
}
105+
106+
template <typename R>
107+
int f(std::map<R*, int>& map, R* r) {
108+
return map[r]; // OK
109+
}
110+
111+
}

0 commit comments

Comments
 (0)