StdAllocatorConstCheck.cpp 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //===-- StdAllocatorConstCheck.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 "StdAllocatorConstCheck.h"
  9. #include "clang/ASTMatchers/ASTMatchFinder.h"
  10. using namespace clang::ast_matchers;
  11. namespace clang::tidy::portability {
  12. void StdAllocatorConstCheck::registerMatchers(MatchFinder *Finder) {
  13. // Match std::allocator<const T>.
  14. auto allocatorConst =
  15. recordType(hasDeclaration(classTemplateSpecializationDecl(
  16. hasName("::std::allocator"),
  17. hasTemplateArgument(0, refersToType(qualType(isConstQualified()))))));
  18. auto hasContainerName =
  19. hasAnyName("::std::vector", "::std::deque", "::std::list",
  20. "::std::multiset", "::std::set", "::std::unordered_multiset",
  21. "::std::unordered_set", "::absl::flat_hash_set");
  22. // Match `std::vector<const T> var;` and other common containers like deque,
  23. // list, and absl::flat_hash_set. Containers like queue and stack use deque
  24. // but do not directly use std::allocator as a template argument, so they
  25. // aren't caught.
  26. Finder->addMatcher(
  27. typeLoc(
  28. templateSpecializationTypeLoc(),
  29. loc(hasUnqualifiedDesugaredType(anyOf(
  30. recordType(hasDeclaration(classTemplateSpecializationDecl(
  31. hasContainerName,
  32. anyOf(
  33. hasTemplateArgument(1, refersToType(allocatorConst)),
  34. hasTemplateArgument(2, refersToType(allocatorConst)),
  35. hasTemplateArgument(3, refersToType(allocatorConst)))))),
  36. // Match std::vector<const dependent>
  37. templateSpecializationType(
  38. templateArgumentCountIs(1),
  39. hasTemplateArgument(
  40. 0, refersToType(qualType(isConstQualified()))),
  41. hasDeclaration(namedDecl(hasContainerName)))))))
  42. .bind("type_loc"),
  43. this);
  44. }
  45. void StdAllocatorConstCheck::check(const MatchFinder::MatchResult &Result) {
  46. const auto *T = Result.Nodes.getNodeAs<TypeLoc>("type_loc");
  47. if (!T)
  48. return;
  49. // Exclude TypeLoc matches in STL headers.
  50. if (isSystem(Result.Context->getSourceManager().getFileCharacteristic(
  51. T->getBeginLoc())))
  52. return;
  53. diag(T->getBeginLoc(),
  54. "container using std::allocator<const T> is a deprecated libc++ "
  55. "extension; remove const for compatibility with other standard "
  56. "libraries");
  57. }
  58. } // namespace clang::tidy::portability