DispatchOnceNonstaticCheck.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //===--- DispatchOnceNonstaticCheck.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 "DispatchOnceNonstaticCheck.h"
  9. #include "clang/AST/ASTContext.h"
  10. #include "clang/AST/Decl.h"
  11. #include "clang/AST/DeclObjC.h"
  12. #include "clang/ASTMatchers/ASTMatchFinder.h"
  13. #include "clang/ASTMatchers/ASTMatchers.h"
  14. #include "clang/Basic/Diagnostic.h"
  15. using namespace clang::ast_matchers;
  16. namespace clang::tidy::darwin {
  17. void DispatchOnceNonstaticCheck::registerMatchers(MatchFinder *Finder) {
  18. // Find variables without static or global storage. VarDecls do not include
  19. // struct/class members, which are FieldDecls.
  20. Finder->addMatcher(
  21. varDecl(hasLocalStorage(), hasType(asString("dispatch_once_t")))
  22. .bind("non-static-var"),
  23. this);
  24. // Members of structs or classes might be okay, if the use is at static or
  25. // global scope. These will be ignored for now. But ObjC ivars can be
  26. // flagged immediately, since they cannot be static.
  27. Finder->addMatcher(
  28. objcIvarDecl(hasType(asString("dispatch_once_t"))).bind("ivar"), this);
  29. }
  30. void DispatchOnceNonstaticCheck::check(const MatchFinder::MatchResult &Result) {
  31. if (const auto *VD = Result.Nodes.getNodeAs<VarDecl>("non-static-var")) {
  32. if (const auto *PD = dyn_cast<ParmVarDecl>(VD)) {
  33. // Catch function/method parameters, as any dispatch_once_t should be
  34. // passed by pointer instead.
  35. diag(PD->getTypeSpecStartLoc(),
  36. "dispatch_once_t variables must have static or global storage "
  37. "duration; function parameters should be pointer references");
  38. } else {
  39. diag(VD->getTypeSpecStartLoc(), "dispatch_once_t variables must have "
  40. "static or global storage duration")
  41. << FixItHint::CreateInsertion(VD->getTypeSpecStartLoc(), "static ");
  42. }
  43. }
  44. if (const auto *D = Result.Nodes.getNodeAs<ObjCIvarDecl>("ivar")) {
  45. diag(D->getTypeSpecStartLoc(),
  46. "dispatch_once_t variables must have static or global storage "
  47. "duration and cannot be Objective-C instance variables");
  48. }
  49. }
  50. } // namespace clang::tidy::darwin