clang-tools  8.0.0
AvoidCArraysCheck.cpp
Go to the documentation of this file.
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
AST_MATCHER(BinaryOperator, isAssignmentOperator)
Definition: Matchers.h:20
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
AST_MATCHER_P(FunctionDecl, throws, internal::Matcher< Type >, InnerMatcher)