xref: /llvm-project/clang-tools-extra/clang-tidy/linuxkernel/MustCheckErrsCheck.cpp (revision fc2a9ad10e21bda3dafbb85d8317ef5e3e5f99a1)
1 //===--- MustCheckErrsCheck.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 
9 #include "MustCheckErrsCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 
13 using namespace clang::ast_matchers;
14 
15 namespace clang::tidy::linuxkernel {
16 
registerMatchers(MatchFinder * Finder)17 void MustCheckErrsCheck::registerMatchers(MatchFinder *Finder) {
18   auto ErrFn =
19       functionDecl(hasAnyName("ERR_PTR", "PTR_ERR", "IS_ERR", "IS_ERR_OR_NULL",
20                               "ERR_CAST", "PTR_ERR_OR_ZERO"));
21   auto NonCheckingStmts = stmt(anyOf(compoundStmt(), labelStmt()));
22   Finder->addMatcher(
23       callExpr(callee(ErrFn), hasParent(NonCheckingStmts)).bind("call"),
24       this);
25 
26   auto ReturnToCheck = returnStmt(hasReturnValue(callExpr(callee(ErrFn))));
27   auto ReturnsErrFn = functionDecl(hasDescendant(ReturnToCheck));
28   Finder->addMatcher(callExpr(callee(ReturnsErrFn), hasParent(NonCheckingStmts))
29                          .bind("transitive_call"),
30                      this);
31 }
32 
check(const MatchFinder::MatchResult & Result)33 void MustCheckErrsCheck::check(const MatchFinder::MatchResult &Result) {
34   const auto *MatchedCallExpr = Result.Nodes.getNodeAs<CallExpr>("call");
35   if (MatchedCallExpr) {
36     diag(MatchedCallExpr->getExprLoc(), "result from function %0 is unused")
37         << MatchedCallExpr->getDirectCallee();
38   }
39 
40   const auto *MatchedTransitiveCallExpr =
41       Result.Nodes.getNodeAs<CallExpr>("transitive_call");
42   if (MatchedTransitiveCallExpr) {
43     diag(MatchedTransitiveCallExpr->getExprLoc(),
44          "result from function %0 is unused but represents an error value")
45         << MatchedTransitiveCallExpr->getDirectCallee();
46   }
47 }
48 
49 } // namespace clang::tidy::linuxkernel
50