Skip to content

Commit 2634bd5

Browse files
committed
[clang-tidy] Avoid C arrays check
Summary: [[ https://bugs.llvm.org/show_bug.cgi?id=39224 | PR39224 ]] As discussed, we can't always do the transform automatically due to that array-to-pointer decay of C array. In order to detect whether we can do said transform, we'd need to be able to see all usages of said array, which is, i would say, rather impossible if e.g. it is in the header. Thus right now no fixit exists. Exceptions: `extern "C"` code. References: * [[ https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es27-use-stdarray-or-stack_array-for-arrays-on-the-stack | CPPCG ES.27: Use std::array or stack_array for arrays on the stack ]] * [[ https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#slcon1-prefer-using-stl-array-or-vector-instead-of-a-c-array | CPPCG SL.con.1: Prefer using STL array or vector instead of a C array ]] * HICPP `4.1.1 Ensure that a function argument does not undergo an array-to-pointer conversion` * MISRA `5-2-12 An identifier with array type passed as a function argument shall not decay to a pointer` Reviewers: aaron.ballman, JonasToth, alexfh, hokein, xazax.hun Reviewed By: JonasToth Subscribers: Eugene.Zelenko, mgorny, rnkovacs, cfe-commits Tags: #clang-tools-extra Differential Revision: https://reviews.llvm.org/D53771 llvm-svn: 346835
1 parent 789cc81 commit 2634bd5

13 files changed

+297
-0
lines changed

clang-tools-extra/clang-tidy/cppcoreguidelines/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ add_clang_library(clangTidyCppCoreGuidelinesModule
2828
clangLex
2929
clangTidy
3030
clangTidyMiscModule
31+
clangTidyModernizeModule
3132
clangTidyReadabilityModule
3233
clangTidyUtils
3334
clangTooling

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
#include "../ClangTidyModuleRegistry.h"
1313
#include "../misc/NonPrivateMemberVariablesInClassesCheck.h"
1414
#include "../misc/UnconventionalAssignOperatorCheck.h"
15+
#include "../modernize/AvoidCArraysCheck.h"
1516
#include "../readability/MagicNumbersCheck.h"
1617
#include "AvoidGotoCheck.h"
1718
#include "InterfacesGlobalInitCheck.h"
@@ -40,6 +41,8 @@ namespace cppcoreguidelines {
4041
class CppCoreGuidelinesModule : public ClangTidyModule {
4142
public:
4243
void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
44+
CheckFactories.registerCheck<modernize::AvoidCArraysCheck>(
45+
"cppcoreguidelines-avoid-c-arrays");
4346
CheckFactories.registerCheck<AvoidGotoCheck>(
4447
"cppcoreguidelines-avoid-goto");
4548
CheckFactories.registerCheck<readability::MagicNumbersCheck>(

clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#include "../misc/NewDeleteOverloadsCheck.h"
2323
#include "../misc/StaticAssertCheck.h"
2424
#include "../bugprone/UndelegatedConstructorCheck.h"
25+
#include "../modernize/AvoidCArraysCheck.h"
2526
#include "../modernize/DeprecatedHeadersCheck.h"
2627
#include "../modernize/UseAutoCheck.h"
2728
#include "../modernize/UseEmplaceCheck.h"
@@ -48,6 +49,8 @@ namespace hicpp {
4849
class HICPPModule : public ClangTidyModule {
4950
public:
5051
void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
52+
CheckFactories.registerCheck<modernize::AvoidCArraysCheck>(
53+
"hicpp-avoid-c-arrays");
5154
CheckFactories.registerCheck<cppcoreguidelines::AvoidGotoCheck>(
5255
"hicpp-avoid-goto");
5356
CheckFactories.registerCheck<readability::BracesAroundStatementsCheck>(
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
//===--- AvoidCArraysCheck.cpp - clang-tidy -------------------------------===//
2+
//
3+
// The LLVM Compiler Infrastructure
4+
//
5+
// This file is distributed under the University of Illinois Open Source
6+
// License. See LICENSE.TXT for details.
7+
//
8+
//===----------------------------------------------------------------------===//
9+
10+
#include "AvoidCArraysCheck.h"
11+
#include "clang/AST/ASTContext.h"
12+
#include "clang/ASTMatchers/ASTMatchFinder.h"
13+
14+
using namespace clang::ast_matchers;
15+
16+
namespace {
17+
18+
AST_MATCHER(clang::TypeLoc, hasValidBeginLoc) {
19+
return Node.getBeginLoc().isValid();
20+
}
21+
22+
AST_MATCHER_P(clang::TypeLoc, hasType,
23+
clang::ast_matchers::internal::Matcher<clang::Type>,
24+
InnerMatcher) {
25+
const clang::Type *TypeNode = Node.getTypePtr();
26+
return TypeNode != nullptr &&
27+
InnerMatcher.matches(*TypeNode, Finder, Builder);
28+
}
29+
30+
AST_MATCHER(clang::RecordDecl, isExternCContext) {
31+
return Node.isExternCContext();
32+
}
33+
34+
} // namespace
35+
36+
namespace clang {
37+
namespace tidy {
38+
namespace modernize {
39+
40+
void AvoidCArraysCheck::registerMatchers(MatchFinder *Finder) {
41+
// std::array<> is avaliable since C++11.
42+
if (!getLangOpts().CPlusPlus11)
43+
return;
44+
45+
Finder->addMatcher(
46+
typeLoc(hasValidBeginLoc(), hasType(arrayType()),
47+
unless(anyOf(hasParent(varDecl(isExternC())),
48+
hasParent(fieldDecl(
49+
hasParent(recordDecl(isExternCContext())))),
50+
hasAncestor(functionDecl(isExternC())))))
51+
.bind("typeloc"),
52+
this);
53+
}
54+
55+
void AvoidCArraysCheck::check(const MatchFinder::MatchResult &Result) {
56+
const auto *ArrayType = Result.Nodes.getNodeAs<TypeLoc>("typeloc");
57+
58+
static constexpr llvm::StringLiteral UseArray = llvm::StringLiteral(
59+
"do not declare C-style arrays, use std::array<> instead");
60+
static constexpr llvm::StringLiteral UseVector = llvm::StringLiteral(
61+
"do not declare C VLA arrays, use std::vector<> instead");
62+
63+
diag(ArrayType->getBeginLoc(),
64+
ArrayType->getTypePtr()->isVariableArrayType() ? UseVector : UseArray);
65+
}
66+
67+
} // namespace modernize
68+
} // namespace tidy
69+
} // namespace clang
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
//===--- AvoidCArraysCheck.h - clang-tidy -----------------------*- C++ -*-===//
2+
//
3+
// The LLVM Compiler Infrastructure
4+
//
5+
// This file is distributed under the University of Illinois Open Source
6+
// License. See LICENSE.TXT for details.
7+
//
8+
//===----------------------------------------------------------------------===//
9+
10+
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_AVOIDCARRAYSCHECK_H
11+
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_AVOIDCARRAYSCHECK_H
12+
13+
#include "../ClangTidy.h"
14+
15+
namespace clang {
16+
namespace tidy {
17+
namespace modernize {
18+
19+
/// Find C-style array types and recommend to use std::array<> / std::vector<>.
20+
///
21+
/// For the user-facing documentation see:
22+
/// http://clang.llvm.org/extra/clang-tidy/checks/modernize-avoid-c-arrays.html
23+
class AvoidCArraysCheck : public ClangTidyCheck {
24+
public:
25+
AvoidCArraysCheck(StringRef Name, ClangTidyContext *Context)
26+
: ClangTidyCheck(Name, Context) {}
27+
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
28+
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
29+
};
30+
31+
} // namespace modernize
32+
} // namespace tidy
33+
} // namespace clang
34+
35+
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_AVOIDCARRAYSCHECK_H

clang-tools-extra/clang-tidy/modernize/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ set(LLVM_LINK_COMPONENTS support)
22

33
add_clang_library(clangTidyModernizeModule
44
AvoidBindCheck.cpp
5+
AvoidCArraysCheck.cpp
56
ConcatNestedNamespacesCheck.cpp
67
DeprecatedHeadersCheck.cpp
78
DeprecatedIosBaseAliasesCheck.cpp

clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#include "../ClangTidyModule.h"
1212
#include "../ClangTidyModuleRegistry.h"
1313
#include "AvoidBindCheck.h"
14+
#include "AvoidCArraysCheck.h"
1415
#include "ConcatNestedNamespacesCheck.h"
1516
#include "DeprecatedHeadersCheck.h"
1617
#include "DeprecatedIosBaseAliasesCheck.h"
@@ -48,6 +49,7 @@ class ModernizeModule : public ClangTidyModule {
4849
public:
4950
void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
5051
CheckFactories.registerCheck<AvoidBindCheck>("modernize-avoid-bind");
52+
CheckFactories.registerCheck<AvoidCArraysCheck>("modernize-avoid-c-arrays");
5153
CheckFactories.registerCheck<ConcatNestedNamespacesCheck>(
5254
"modernize-concat-nested-namespaces");
5355
CheckFactories.registerCheck<DeprecatedHeadersCheck>(

clang-tools-extra/docs/ReleaseNotes.rst

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,12 @@ Improvements to clang-tidy
130130
but also have logic (non-static member functions), and diagnoses all member
131131
variables that have any other scope other than ``private``.
132132

133+
- New :doc:`modernize-avoid-c-arrays
134+
<clang-tidy/checks/modernize-avoid-c-arrays>` check.
135+
136+
Finds C-style array types and recommend to use ``std::array<>`` /
137+
``std::vector<>``.
138+
133139
- New :doc:`modernize-concat-nested-namespaces
134140
<clang-tidy/checks/modernize-concat-nested-namespaces>` check.
135141

@@ -173,12 +179,22 @@ Improvements to clang-tidy
173179
<clang-tidy/checks/readability-uppercase-literal-suffix>`
174180
added.
175181

182+
- New alias :doc:`cppcoreguidelines-avoid-c-arrays
183+
<clang-tidy/checks/cppcoreguidelines-avoid-c-arrays>`
184+
to :doc:`modernize-avoid-c-arrays
185+
<clang-tidy/checks/modernize-avoid-c-arrays>` added.
186+
176187
- New alias :doc:`cppcoreguidelines-non-private-member-variables-in-classes
177188
<clang-tidy/checks/cppcoreguidelines-non-private-member-variables-in-classes>`
178189
to :doc:`misc-non-private-member-variables-in-classes
179190
<clang-tidy/checks/misc-non-private-member-variables-in-classes>`
180191
added.
181192

193+
- New alias :doc:`hicpp-avoid-c-arrays
194+
<clang-tidy/checks/hicpp-avoid-c-arrays>`
195+
to :doc:`modernize-avoid-c-arrays
196+
<clang-tidy/checks/modernize-avoid-c-arrays>` added.
197+
182198
- New alias :doc:`hicpp-uppercase-literal-suffix
183199
<clang-tidy/checks/hicpp-uppercase-literal-suffix>` to
184200
:doc:`readability-uppercase-literal-suffix
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
.. title:: clang-tidy - cppcoreguidelines-avoid-c-arrays
2+
.. meta::
3+
:http-equiv=refresh: 5;URL=modernize-avoid-c-arrays.html
4+
5+
cppcoreguidelines-avoid-c-arrays
6+
================================
7+
8+
The cppcoreguidelines-avoid-c-arrays check is an alias, please see
9+
`modernize-avoid-c-arrays <modernize-avoid-c-arrays.html>`_
10+
for more information.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
.. title:: clang-tidy - hicpp-avoid-c-arrays
2+
.. meta::
3+
:http-equiv=refresh: 5;URL=modernize-avoid-c-arrays.html
4+
5+
hicpp-avoid-c-arrays
6+
====================
7+
8+
The hicpp-avoid-c-arrays check is an alias, please see
9+
`modernize-avoid-c-arrays <modernize-avoid-c-arrays.html>`_
10+
for more information.

clang-tools-extra/docs/clang-tidy/checks/list.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ Clang-Tidy Checks
8888
cert-msc51-cpp
8989
cert-oop11-cpp (redirects to performance-move-constructor-init) <cert-oop11-cpp>
9090
cppcoreguidelines-avoid-goto
91+
cppcoreguidelines-avoid-c-arrays (redirects to modernize-avoid-c-arrays) <cppcoreguidelines-avoid-c-arrays>
9192
cppcoreguidelines-avoid-magic-numbers (redirects to readability-magic-numbers) <cppcoreguidelines-avoid-magic-numbers>
9293
cppcoreguidelines-c-copy-assignment-signature (redirects to misc-unconventional-assign-operator) <cppcoreguidelines-c-copy-assignment-signature>
9394
cppcoreguidelines-interfaces-global-init
@@ -132,6 +133,7 @@ Clang-Tidy Checks
132133
google-runtime-int
133134
google-runtime-operator
134135
google-runtime-references
136+
hicpp-avoid-c-arrays (redirects to modernize-avoid-c-arrays) <hicpp-avoid-c-arrays>
135137
hicpp-avoid-goto
136138
hicpp-braces-around-statements (redirects to readability-braces-around-statements) <hicpp-braces-around-statements>
137139
hicpp-deprecated-headers (redirects to modernize-deprecated-headers) <hicpp-deprecated-headers>
@@ -179,6 +181,7 @@ Clang-Tidy Checks
179181
misc-unused-parameters
180182
misc-unused-using-decls
181183
modernize-avoid-bind
184+
modernize-avoid-c-arrays
182185
modernize-concat-nested-namespaces
183186
modernize-deprecated-headers
184187
modernize-deprecated-ios-base-aliases
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
.. title:: clang-tidy - modernize-avoid-c-arrays
2+
3+
modernize-avoid-c-arrays
4+
========================
5+
6+
`cppcoreguidelines-avoid-c-arrays` redirects here as an alias for this check.
7+
8+
`hicpp-avoid-c-arrays` redirects here as an alias for this check.
9+
10+
Finds C-style array types and recommend to use ``std::array<>`` /
11+
``std::vector<>``. All types of C arrays are diagnosed.
12+
13+
However, fix-it are potentially dangerous in header files and are therefore not
14+
emitted right now.
15+
16+
.. code:: c++
17+
18+
int a[] = {1, 2}; // warning: do not declare C-style arrays, use std::array<> instead
19+
20+
int b[1]; // warning: do not declare C-style arrays, use std::array<> instead
21+
22+
void foo() {
23+
int c[b[0]]; // warning: do not declare C VLA arrays, use std::vector<> instead
24+
}
25+
26+
template <typename T, int Size>
27+
class array {
28+
T d[Size]; // warning: do not declare C-style arrays, use std::array<> instead
29+
30+
int e[1]; // warning: do not declare C-style arrays, use std::array<> instead
31+
};
32+
33+
array<int[4], 2> d; // warning: do not declare C-style arrays, use std::array<> instead
34+
35+
using k = int[4]; // warning: do not declare C-style arrays, use std::array<> instead
36+
37+
38+
However, the ``extern "C"`` code is ignored, since it is common to share
39+
such headers between C code, and C++ code.
40+
41+
.. code:: c++
42+
43+
// Some header
44+
extern "C" {
45+
46+
int f[] = {1, 2}; // not diagnosed
47+
48+
int j[1]; // not diagnosed
49+
50+
inline void bar() {
51+
{
52+
int j[j[0]]; // not diagnosed
53+
}
54+
}
55+
56+
}
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
// RUN: %check_clang_tidy %s modernize-avoid-c-arrays %t
2+
3+
int a[] = {1, 2};
4+
// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: do not declare C-style arrays, use std::array<> instead
5+
6+
int b[1];
7+
// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: do not declare C-style arrays, use std::array<> instead
8+
9+
void foo() {
10+
int c[b[0]];
11+
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare C VLA arrays, use std::vector<> instead
12+
13+
using d = decltype(c);
14+
d e;
15+
// Semi-FIXME: we do not diagnose these last two lines separately,
16+
// because we point at typeLoc.getBeginLoc(), which is the decl before that
17+
// (int c[b[0]];), which is already diagnosed.
18+
}
19+
20+
template <typename T, int Size>
21+
class array {
22+
T d[Size];
23+
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare C-style arrays, use std::array<> instead
24+
25+
int e[1];
26+
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare C-style arrays, use std::array<> instead
27+
};
28+
29+
array<int[4], 2> d;
30+
// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: do not declare C-style arrays, use std::array<> instead
31+
32+
using k = int[4];
33+
// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: do not declare C-style arrays, use std::array<> instead
34+
35+
array<k, 2> dk;
36+
37+
template <typename T>
38+
class unique_ptr {
39+
T *d;
40+
41+
int e[1];
42+
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare C-style arrays, use std::array<> instead
43+
};
44+
45+
unique_ptr<int[]> d2;
46+
// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: do not declare C-style arrays, use std::array<> instead
47+
48+
using k2 = int[];
49+
// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: do not declare C-style arrays, use std::array<> instead
50+
51+
unique_ptr<k2> dk2;
52+
53+
// Some header
54+
extern "C" {
55+
56+
int f[] = {1, 2};
57+
58+
int j[1];
59+
60+
inline void bar() {
61+
{
62+
int j[j[0]];
63+
}
64+
}
65+
66+
extern "C++" {
67+
int f3[] = {1, 2};
68+
// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: do not declare C-style arrays, use std::array<> instead
69+
70+
int j3[1];
71+
// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: do not declare C-style arrays, use std::array<> instead
72+
73+
struct Foo {
74+
int f3[3] = {1, 2};
75+
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare C-style arrays, use std::array<> instead
76+
77+
int j3[1];
78+
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare C-style arrays, use std::array<> instead
79+
};
80+
}
81+
82+
struct Bar {
83+
84+
int f[3] = {1, 2};
85+
86+
int j[1];
87+
};
88+
}

0 commit comments

Comments
 (0)