clang-tools 18.0.0git
AvoidCArraysCheck.cpp
Go to the documentation of this file.
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
13using namespace clang::ast_matchers;
14
15namespace {
16
17AST_MATCHER(clang::TypeLoc, hasValidBeginLoc) {
18 return Node.getBeginLoc().isValid();
19}
20
21AST_MATCHER_P(clang::TypeLoc, hasType,
22 clang::ast_matchers::internal::Matcher<clang::Type>,
23 InnerMatcher) {
24 const clang::Type *TypeNode = Node.getTypePtr();
25 return TypeNode != nullptr &&
26 InnerMatcher.matches(*TypeNode, Finder, Builder);
27}
28
29AST_MATCHER(clang::RecordDecl, isExternCContext) {
30 return Node.isExternCContext();
31}
32
33AST_MATCHER(clang::ParmVarDecl, isArgvOfMain) {
34 const clang::DeclContext *DC = Node.getDeclContext();
35 const auto *FD = llvm::dyn_cast<clang::FunctionDecl>(DC);
36 return FD ? FD->isMain() : false;
37}
38
39} // namespace
40
41namespace clang::tidy::modernize {
42
43void AvoidCArraysCheck::registerMatchers(MatchFinder *Finder) {
44 Finder->addMatcher(
45 typeLoc(hasValidBeginLoc(), hasType(arrayType()),
46 unless(anyOf(hasParent(parmVarDecl(isArgvOfMain())),
47 hasParent(varDecl(isExternC())),
48 hasParent(fieldDecl(
49 hasParent(recordDecl(isExternCContext())))),
50 hasAncestor(functionDecl(isExternC())))))
51 .bind("typeloc"),
52 this);
53}
54
55void AvoidCArraysCheck::check(const MatchFinder::MatchResult &Result) {
56 const auto *ArrayType = Result.Nodes.getNodeAs<TypeLoc>("typeloc");
57
58 diag(ArrayType->getBeginLoc(),
59 "do not declare %select{C-style|C VLA}0 arrays, use "
60 "%select{std::array<>|std::vector<>}0 instead")
61 << ArrayType->getTypePtr()->isVariableArrayType();
62}
63
64} // namespace clang::tidy::modernize
CodeCompletionBuilder Builder
::clang::DynTypedNode Node
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
AST_MATCHER_P(UserDefinedLiteral, hasLiteral, clang::ast_matchers::internal::Matcher< Expr >, InnerMatcher)
AST_MATCHER(Decl, declHasNoReturnAttr)
matches a Decl if it has a "no return" attribute of any kind