1 //===--- NoMallocCheck.cpp - clang-tidy------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "NoMallocCheck.h"
10 #include "../utils/Matchers.h"
11 #include "../utils/OptionsUtils.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/ASTMatchers/ASTMatchFinder.h"
18 using namespace clang::ast_matchers
;
19 using namespace clang::ast_matchers::internal
;
21 namespace clang::tidy::cppcoreguidelines
{
23 void NoMallocCheck::storeOptions(ClangTidyOptions::OptionMap
&Opts
) {
24 Options
.store(Opts
, "Allocations", AllocList
);
25 Options
.store(Opts
, "Reallocations", ReallocList
);
26 Options
.store(Opts
, "Deallocations", DeallocList
);
29 void NoMallocCheck::registerMatchers(MatchFinder
*Finder
) {
30 // Registering malloc, will suggest RAII.
31 Finder
->addMatcher(callExpr(callee(functionDecl(hasAnyName(
32 utils::options::parseStringList(AllocList
)))))
36 // Registering realloc calls, suggest std::vector or std::string.
38 callExpr(callee(functionDecl(
39 hasAnyName(utils::options::parseStringList((ReallocList
))))))
43 // Registering free calls, will suggest RAII instead.
45 callExpr(callee(functionDecl(
46 hasAnyName(utils::options::parseStringList((DeallocList
))))))
51 void NoMallocCheck::check(const MatchFinder::MatchResult
&Result
) {
52 const CallExpr
*Call
= nullptr;
53 StringRef Recommendation
;
55 if ((Call
= Result
.Nodes
.getNodeAs
<CallExpr
>("allocation")))
56 Recommendation
= "consider a container or a smart pointer";
57 else if ((Call
= Result
.Nodes
.getNodeAs
<CallExpr
>("realloc")))
58 Recommendation
= "consider std::vector or std::string";
59 else if ((Call
= Result
.Nodes
.getNodeAs
<CallExpr
>("free")))
60 Recommendation
= "use RAII";
62 assert(Call
&& "Unhandled binding in the Matcher");
64 diag(Call
->getBeginLoc(), "do not manage memory manually; %0")
65 << Recommendation
<< SourceRange(Call
->getBeginLoc(), Call
->getEndLoc());
68 } // namespace clang::tidy::cppcoreguidelines