AvoidCArraysCheck.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. #include "AvoidCArraysCheck.h"
  9. #include "clang/AST/ASTContext.h"
  10. #include "clang/ASTMatchers/ASTMatchFinder.h"
  11. using namespace clang::ast_matchers;
  12. namespace {
  13. AST_MATCHER(clang::TypeLoc, hasValidBeginLoc) {
  14. return Node.getBeginLoc().isValid();
  15. }
  16. AST_MATCHER_P(clang::TypeLoc, hasType,
  17. clang::ast_matchers::internal::Matcher<clang::Type>,
  18. InnerMatcher) {
  19. const clang::Type *TypeNode = Node.getTypePtr();
  20. return TypeNode != nullptr &&
  21. InnerMatcher.matches(*TypeNode, Finder, Builder);
  22. }
  23. AST_MATCHER(clang::RecordDecl, isExternCContext) {
  24. return Node.isExternCContext();
  25. }
  26. AST_MATCHER(clang::ParmVarDecl, isArgvOfMain) {
  27. const clang::DeclContext *DC = Node.getDeclContext();
  28. const auto *FD = llvm::dyn_cast<clang::FunctionDecl>(DC);
  29. return FD ? FD->isMain() : false;
  30. }
  31. } // namespace
  32. namespace clang::tidy::modernize {
  33. void AvoidCArraysCheck::registerMatchers(MatchFinder *Finder) {
  34. Finder->addMatcher(
  35. typeLoc(hasValidBeginLoc(), hasType(arrayType()),
  36. unless(anyOf(hasParent(parmVarDecl(isArgvOfMain())),
  37. hasParent(varDecl(isExternC())),
  38. hasParent(fieldDecl(
  39. hasParent(recordDecl(isExternCContext())))),
  40. hasAncestor(functionDecl(isExternC())))))
  41. .bind("typeloc"),
  42. this);
  43. }
  44. void AvoidCArraysCheck::check(const MatchFinder::MatchResult &Result) {
  45. const auto *ArrayType = Result.Nodes.getNodeAs<TypeLoc>("typeloc");
  46. diag(ArrayType->getBeginLoc(),
  47. "do not declare %select{C-style|C VLA}0 arrays, use "
  48. "%select{std::array<>|std::vector<>}0 instead")
  49. << ArrayType->getTypePtr()->isVariableArrayType();
  50. }
  51. } // namespace clang::tidy::modernize