UseNodiscardCheck.cpp 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. //===--- UseNodiscardCheck.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 "UseNodiscardCheck.h"
  9. #include "clang/AST/ASTContext.h"
  10. #include "clang/AST/Decl.h"
  11. #include "clang/AST/Type.h"
  12. #include "clang/ASTMatchers/ASTMatchFinder.h"
  13. using namespace clang::ast_matchers;
  14. namespace clang::tidy::modernize {
  15. static bool doesNoDiscardMacroExist(ASTContext &Context,
  16. const llvm::StringRef &MacroId) {
  17. // Don't check for the Macro existence if we are using an attribute
  18. // either a C++17 standard attribute or pre C++17 syntax
  19. if (MacroId.startswith("[[") || MacroId.startswith("__attribute__"))
  20. return true;
  21. // Otherwise look up the macro name in the context to see if its defined.
  22. return Context.Idents.get(MacroId).hasMacroDefinition();
  23. }
  24. namespace {
  25. AST_MATCHER(CXXMethodDecl, isOverloadedOperator) {
  26. // Don't put ``[[nodiscard]]`` in front of operators.
  27. return Node.isOverloadedOperator();
  28. }
  29. AST_MATCHER(CXXMethodDecl, isConversionOperator) {
  30. // Don't put ``[[nodiscard]]`` in front of a conversion decl
  31. // like operator bool().
  32. return isa<CXXConversionDecl>(Node);
  33. }
  34. AST_MATCHER(CXXMethodDecl, hasClassMutableFields) {
  35. // Don't put ``[[nodiscard]]`` on functions on classes with
  36. // mutable member variables.
  37. return Node.getParent()->hasMutableFields();
  38. }
  39. AST_MATCHER(ParmVarDecl, hasParameterPack) {
  40. // Don't put ``[[nodiscard]]`` on functions with parameter pack arguments.
  41. return Node.isParameterPack();
  42. }
  43. AST_MATCHER(CXXMethodDecl, hasTemplateReturnType) {
  44. // Don't put ``[[nodiscard]]`` in front of functions returning a template
  45. // type.
  46. return Node.getReturnType()->isTemplateTypeParmType() ||
  47. Node.getReturnType()->isInstantiationDependentType();
  48. }
  49. AST_MATCHER(CXXMethodDecl, isDefinitionOrInline) {
  50. // A function definition, with optional inline but not the declaration.
  51. return !(Node.isThisDeclarationADefinition() && Node.isOutOfLine());
  52. }
  53. AST_MATCHER(QualType, isInstantiationDependentType) {
  54. return Node->isInstantiationDependentType();
  55. }
  56. AST_MATCHER(QualType, isNonConstReferenceOrPointer) {
  57. // If the function has any non-const-reference arguments
  58. // bool foo(A &a)
  59. // or pointer arguments
  60. // bool foo(A*)
  61. // then they may not care about the return value because of passing data
  62. // via the arguments.
  63. return (Node->isTemplateTypeParmType() || Node->isPointerType() ||
  64. (Node->isReferenceType() &&
  65. !Node.getNonReferenceType().isConstQualified()) ||
  66. Node->isInstantiationDependentType());
  67. }
  68. } // namespace
  69. UseNodiscardCheck::UseNodiscardCheck(StringRef Name, ClangTidyContext *Context)
  70. : ClangTidyCheck(Name, Context),
  71. NoDiscardMacro(Options.get("ReplacementString", "[[nodiscard]]")) {}
  72. void UseNodiscardCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
  73. Options.store(Opts, "ReplacementString", NoDiscardMacro);
  74. }
  75. void UseNodiscardCheck::registerMatchers(MatchFinder *Finder) {
  76. auto FunctionObj =
  77. cxxRecordDecl(hasAnyName("::std::function", "::boost::function"));
  78. // Find all non-void const methods which have not already been marked to
  79. // warn on unused result.
  80. Finder->addMatcher(
  81. cxxMethodDecl(
  82. allOf(isConst(), isDefinitionOrInline(),
  83. unless(anyOf(
  84. returns(voidType()),
  85. returns(hasDeclaration(decl(hasAttr(clang::attr::WarnUnusedResult)))),
  86. isNoReturn(), isOverloadedOperator(),
  87. isVariadic(), hasTemplateReturnType(),
  88. hasClassMutableFields(), isConversionOperator(),
  89. hasAttr(clang::attr::WarnUnusedResult),
  90. hasType(isInstantiationDependentType()),
  91. hasAnyParameter(anyOf(
  92. parmVarDecl(anyOf(hasType(FunctionObj),
  93. hasType(references(FunctionObj)))),
  94. hasType(isNonConstReferenceOrPointer()),
  95. hasParameterPack()))))))
  96. .bind("no_discard"),
  97. this);
  98. }
  99. void UseNodiscardCheck::check(const MatchFinder::MatchResult &Result) {
  100. const auto *MatchedDecl = Result.Nodes.getNodeAs<CXXMethodDecl>("no_discard");
  101. // Don't make replacements if the location is invalid or in a macro.
  102. SourceLocation Loc = MatchedDecl->getLocation();
  103. if (Loc.isInvalid() || Loc.isMacroID())
  104. return;
  105. SourceLocation RetLoc = MatchedDecl->getInnerLocStart();
  106. ASTContext &Context = *Result.Context;
  107. auto Diag = diag(RetLoc, "function %0 should be marked %1")
  108. << MatchedDecl << NoDiscardMacro;
  109. // Check for the existence of the keyword being used as the ``[[nodiscard]]``.
  110. if (!doesNoDiscardMacroExist(Context, NoDiscardMacro))
  111. return;
  112. // Possible false positives include:
  113. // 1. A const member function which returns a variable which is ignored
  114. // but performs some external I/O operation and the return value could be
  115. // ignored.
  116. Diag << FixItHint::CreateInsertion(RetLoc, (NoDiscardMacro + " ").str());
  117. }
  118. bool UseNodiscardCheck::isLanguageVersionSupported(
  119. const LangOptions &LangOpts) const {
  120. // If we use ``[[nodiscard]]`` attribute, we require at least C++17. Use a
  121. // macro or ``__attribute__`` with pre c++17 compilers by using
  122. // ReplacementString option.
  123. if (NoDiscardMacro == "[[nodiscard]]")
  124. return LangOpts.CPlusPlus17;
  125. return LangOpts.CPlusPlus;
  126. }
  127. } // namespace clang::tidy::modernize