ContainerSizeEmptyCheck.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. //===--- ContainerSizeEmptyCheck.h - clang-tidy -----------------*- C++ -*-===//
  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. #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_CONTAINERSIZEEMPTYCHECK_H
  9. #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_CONTAINERSIZEEMPTYCHECK_H
  10. #include "../ClangTidyCheck.h"
  11. namespace clang::tidy::readability {
  12. /// Checks whether a call to the `size()` method can be replaced with a call to
  13. /// `empty()`.
  14. ///
  15. /// The emptiness of a container should be checked using the `empty()` method
  16. /// instead of the `size()` method. It is not guaranteed that `size()` is a
  17. /// constant-time function, and it is generally more efficient and also shows
  18. /// clearer intent to use `empty()`. Furthermore some containers may implement
  19. /// the `empty()` method but not implement the `size()` method. Using `empty()`
  20. /// whenever possible makes it easier to switch to another container in the
  21. /// future.
  22. class ContainerSizeEmptyCheck : public ClangTidyCheck {
  23. public:
  24. ContainerSizeEmptyCheck(StringRef Name, ClangTidyContext *Context);
  25. bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
  26. return LangOpts.CPlusPlus;
  27. }
  28. void registerMatchers(ast_matchers::MatchFinder *Finder) override;
  29. void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
  30. std::optional<TraversalKind> getCheckTraversalKind() const override {
  31. return TK_IgnoreUnlessSpelledInSource;
  32. }
  33. };
  34. } // namespace clang::tidy::readability
  35. #endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_CONTAINERSIZEEMPTYCHECK_H