Debian Codegraph @

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

raw
1 //===--- AvoidCArraysCheck.cpp - clang-tidy -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "AvoidCArraysCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12
13 using namespace clang::ast_matchers;
14
15 namespace clang::tidy::modernize {
16
17 namespace {
18
19 AST_MATCHER(clang::TypeLoc, hasValidBeginLoc) {
20 return Node.getBeginLoc().isValid();
21 }
22
23 AST_MATCHER_P(clang::TypeLoc, hasType,
24 clang::ast_matchers::internal::Matcher<clang::Type>,
25 InnerMatcher) {
26 const clang::Type *TypeNode = Node.getTypePtr();
27 return TypeNode != nullptr &&
28 InnerMatcher.matches(*TypeNode, Finder, Builder);
29 }
30
31 AST_MATCHER(clang::RecordDecl, isExternCContext) {
32 return Node.isExternCContext();
33 }
34
35 AST_MATCHER(clang::ParmVarDecl, isArgvOfMain) {
36 const clang::DeclContext *DC = Node.getDeclContext();
37 const auto *FD = llvm::dyn_cast<clang::FunctionDecl>(DC);
38 return FD ? FD->isMain() : false;
39 }
40
41 } // namespace
42
43 AvoidCArraysCheck::AvoidCArraysCheck(StringRef Name, ClangTidyContext *Context)
44 : ClangTidyCheck(Name, Context),
45 AllowStringArrays(Options.get("AllowStringArrays", false)) {}
46
47 void AvoidCArraysCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
48 Options.store(Opts, "AllowStringArrays", AllowStringArrays);
49 }
50
51 void AvoidCArraysCheck::registerMatchers(MatchFinder *Finder) {
52 ast_matchers::internal::Matcher<TypeLoc> IgnoreStringArrayIfNeededMatcher =
53 anything();
54 if (AllowStringArrays)
55 IgnoreStringArrayIfNeededMatcher =
56 unless(typeLoc(loc(hasCanonicalType(incompleteArrayType(
57 hasElementType(isAnyCharacter())))),
58 hasParent(varDecl(hasInitializer(stringLiteral()),
59 unless(parmVarDecl())))));
60
61 Finder->addMatcher(
62 typeLoc(hasValidBeginLoc(), hasType(arrayType()),
63 unless(anyOf(hasParent(parmVarDecl(isArgvOfMain())),
64 hasParent(varDecl(isExternC())),
65 hasParent(fieldDecl(
66 hasParent(recordDecl(isExternCContext())))),
67 hasAncestor(functionDecl(isExternC())))),
68 std::move(IgnoreStringArrayIfNeededMatcher))
69 .bind("typeloc"),
70 this);
71 }
72
73 void AvoidCArraysCheck::check(const MatchFinder::MatchResult &Result) {
74 const auto *ArrayType = Result.Nodes.getNodeAs<TypeLoc>("typeloc");
75
76 diag(ArrayType->getBeginLoc(),
77 "do not declare %select{C-style|C VLA}0 arrays, use "
78 "%select{std::array<>|std::vector<>}0 instead")
79 << ArrayType->getTypePtr()->isVariableArrayType();
80 }
81
82 } // namespace clang::tidy::modernize