11#include "clang/Frontend/CompilerInstance.h"
12#include "clang/Lex/Lexer.h"
13#include "clang/Lex/Preprocessor.h"
25 const SourceManager &SM,
26 const LangOptions &Lang) {
27 StringRef WrittenName = Lexer::getSourceText(
28 CharSourceRange::getTokenRange(
29 NewExpr->getAllocatedTypeSourceInfo()->getTypeLoc().getSourceRange()),
31 if (NewExpr->isArray()) {
32 return (WrittenName +
"[]").str();
34 return WrittenName.str();
40 StringRef MakeSmartPtrFunctionName)
42 Inserter(Options.getLocalOrGlobal(
"IncludeStyle",
43 utils::IncludeSorter::IS_LLVM),
44 areDiagsSelfContained()),
45 MakeSmartPtrFunctionHeader(
46 Options.get(
"MakeSmartPtrFunctionHeader",
"<memory>")),
47 MakeSmartPtrFunctionName(
48 Options.get(
"MakeSmartPtrFunction", MakeSmartPtrFunctionName)),
49 IgnoreMacros(Options.get(
"IgnoreMacros", true)),
50 IgnoreDefaultInitialization(
51 Options.get(
"IgnoreDefaultInitialization", true)) {}
54 Options.store(Opts,
"IncludeStyle", Inserter.getStyle());
55 Options.store(Opts,
"MakeSmartPtrFunctionHeader", MakeSmartPtrFunctionHeader);
56 Options.store(Opts,
"MakeSmartPtrFunction", MakeSmartPtrFunctionName);
57 Options.store(Opts,
"IgnoreMacros", IgnoreMacros);
58 Options.store(Opts,
"IgnoreDefaultInitialization",
59 IgnoreDefaultInitialization);
63 const LangOptions &LangOpts)
const {
64 return LangOpts.CPlusPlus11;
69 Preprocessor *ModuleExpanderPP) {
70 Inserter.registerPreprocessor(PP);
76 auto CanCallCtor = unless(has(ignoringImpCasts(
77 cxxConstructExpr(hasDeclaration(decl(unless(isPublic())))))));
79 auto IsPlacement = hasAnyPlacementArg(anything());
84 anyOf(hasParent(cxxBindTemporaryExpr()),
88 0, cxxNewExpr(hasType(pointsTo(qualType(hasCanonicalType(
90 CanCallCtor, unless(IsPlacement))
92 unless(isInTemplateInstantiation()))
100 unless(isInTemplateInstantiation()),
101 hasArgument(0, cxxNewExpr(CanCallCtor, unless(IsPlacement))
103 callee(cxxMethodDecl(hasName(
"reset"))),
105 on(ignoringImplicit(anyOf(
117 SourceManager &SM = *Result.SourceManager;
118 const auto *Construct =
120 const auto *DVar = Result.Nodes.getNodeAs<VarDecl>(
DirectVar);
121 const auto *Reset = Result.Nodes.getNodeAs<CXXMemberCallExpr>(
ResetCall);
122 const auto *Type = Result.Nodes.getNodeAs<QualType>(
PointerType);
123 const auto *New = Result.Nodes.getNodeAs<CXXNewExpr>(
NewExpression);
126 if (New->getType()->getPointeeType()->getContainedAutoType())
137 bool Initializes = New->hasInitializer() ||
139 New->getAllocatedType(), *Result.Context);
140 if (!Initializes && IgnoreDefaultInitialization)
143 checkConstruct(SM, Result.Context, Construct, DVar, Type, New);
145 checkReset(SM, Result.Context, Reset, New);
148void MakeSmartPtrCheck::checkConstruct(SourceManager &SM, ASTContext *Ctx,
149 const CXXConstructExpr *Construct,
151 const QualType *Type,
152 const CXXNewExpr *New) {
153 SourceLocation ConstructCallStart = Construct->getExprLoc();
154 bool InMacro = ConstructCallStart.isMacroID();
156 if (InMacro && IgnoreMacros) {
160 bool Invalid =
false;
161 StringRef ExprStr = Lexer::getSourceText(
162 CharSourceRange::getCharRange(
163 ConstructCallStart, Construct->getParenOrBraceRange().getBegin()),
164 SM, getLangOpts(), &Invalid);
168 auto Diag = diag(ConstructCallStart,
"use %0 instead")
169 << MakeSmartPtrFunctionName;
176 if (!replaceNew(Diag, New, SM, Ctx)) {
181 size_t LAngle = ExprStr.find(
'<');
182 SourceLocation ConstructCallEnd;
183 if (LAngle == StringRef::npos) {
186 ConstructCallEnd = ConstructCallStart.getLocWithOffset(ExprStr.size());
187 Diag << FixItHint::CreateInsertion(
188 ConstructCallEnd,
"<" +
getNewExprName(New, SM, getLangOpts()) +
">");
190 ConstructCallEnd = ConstructCallStart.getLocWithOffset(LAngle);
193 std::string FinalMakeSmartPtrFunctionName = MakeSmartPtrFunctionName.str();
195 FinalMakeSmartPtrFunctionName =
196 ExprStr.str() +
" = " + MakeSmartPtrFunctionName.str();
198 Diag << FixItHint::CreateReplacement(
199 CharSourceRange::getCharRange(ConstructCallStart, ConstructCallEnd),
200 FinalMakeSmartPtrFunctionName);
204 if (Construct->isListInitialization()) {
205 SourceRange BraceRange = Construct->getParenOrBraceRange();
206 Diag << FixItHint::CreateReplacement(
207 CharSourceRange::getCharRange(
208 BraceRange.getBegin(), BraceRange.getBegin().getLocWithOffset(1)),
210 Diag << FixItHint::CreateReplacement(
211 CharSourceRange::getCharRange(BraceRange.getEnd(),
212 BraceRange.getEnd().getLocWithOffset(1)),
216 insertHeader(Diag, SM.getFileID(ConstructCallStart));
219void MakeSmartPtrCheck::checkReset(SourceManager &SM, ASTContext *Ctx,
220 const CXXMemberCallExpr *Reset,
221 const CXXNewExpr *New) {
222 const auto *Expr = cast<MemberExpr>(Reset->getCallee());
223 SourceLocation OperatorLoc = Expr->getOperatorLoc();
224 SourceLocation ResetCallStart = Reset->getExprLoc();
225 SourceLocation ExprStart = Expr->getBeginLoc();
226 SourceLocation ExprEnd =
227 Lexer::getLocForEndOfToken(Expr->getEndLoc(), 0, SM, getLangOpts());
229 bool InMacro = ExprStart.isMacroID();
231 if (InMacro && IgnoreMacros) {
238 if (OperatorLoc.isInvalid()) {
242 auto Diag = diag(ResetCallStart,
"use %0 instead")
243 << MakeSmartPtrFunctionName;
250 if (!replaceNew(Diag, New, SM, Ctx)) {
254 Diag << FixItHint::CreateReplacement(
255 CharSourceRange::getCharRange(OperatorLoc, ExprEnd),
256 (llvm::Twine(
" = ") + MakeSmartPtrFunctionName +
"<" +
261 Diag << FixItHint::CreateInsertion(ExprStart,
"*");
263 insertHeader(Diag, SM.getFileID(OperatorLoc));
266bool MakeSmartPtrCheck::replaceNew(DiagnosticBuilder &Diag,
267 const CXXNewExpr *New, SourceManager &SM,
269 auto SkipParensParents = [&](
const Expr *E) {
270 TraversalKindScope RAII(*Ctx, TK_AsIs);
272 for (
const Expr *OldE =
nullptr; E != OldE;) {
274 for (
const auto &Node : Ctx->getParents(*E)) {
275 if (
const Expr *Parent = Node.get<ParenExpr>()) {
284 SourceRange NewRange = SkipParensParents(New)->getSourceRange();
285 SourceLocation NewStart = NewRange.getBegin();
286 SourceLocation NewEnd = NewRange.getEnd();
289 if (NewStart.isInvalid() || NewEnd.isInvalid())
292 std::string ArraySizeExpr;
293 if (
const auto *ArraySize = New->getArraySize().value_or(
nullptr)) {
294 ArraySizeExpr = Lexer::getSourceText(CharSourceRange::getTokenRange(
295 ArraySize->getSourceRange()),
305 auto HasListIntializedArgument = [](
const CXXConstructExpr *CE) {
306 for (
const auto *Arg : CE->arguments()) {
307 Arg = Arg->IgnoreImplicit();
309 if (isa<CXXStdInitializerListExpr>(Arg) || isa<InitListExpr>(Arg))
313 if (
const auto *CEArg = dyn_cast<CXXConstructExpr>(Arg)) {
317 if (CEArg->isElidable()) {
318 if (
const auto *TempExp = CEArg->getArg(0)) {
319 if (
const auto *UnwrappedCE =
320 dyn_cast<CXXConstructExpr>(TempExp->IgnoreImplicit()))
324 if (CEArg->isStdInitListInitialization())
330 switch (New->getInitializationStyle()) {
331 case CXXNewInitializationStyle::None: {
332 if (ArraySizeExpr.empty()) {
333 Diag << FixItHint::CreateRemoval(SourceRange(NewStart, NewEnd));
337 Diag << FixItHint::CreateReplacement(SourceRange(NewStart, NewEnd),
342 case CXXNewInitializationStyle::Parens: {
360 if (
const auto *CE = New->getConstructExpr()) {
361 if (HasListIntializedArgument(CE))
364 if (ArraySizeExpr.empty()) {
365 SourceRange InitRange = New->getDirectInitRange();
366 Diag << FixItHint::CreateRemoval(
367 SourceRange(NewStart, InitRange.getBegin()));
368 Diag << FixItHint::CreateRemoval(SourceRange(InitRange.getEnd(), NewEnd));
373 Diag << FixItHint::CreateReplacement(SourceRange(NewStart, NewEnd),
378 case CXXNewInitializationStyle::Braces: {
380 SourceRange InitRange;
381 if (
const auto *NewConstruct = New->getConstructExpr()) {
382 if (NewConstruct->isStdInitListInitialization() ||
383 HasListIntializedArgument(NewConstruct)) {
406 InitRange = SourceRange(
407 NewConstruct->getParenOrBraceRange().getBegin().getLocWithOffset(1),
408 NewConstruct->getParenOrBraceRange().getEnd().getLocWithOffset(-1));
419 if (
const CXXRecordDecl *RD = New->getType()->getPointeeCXXRecordDecl()) {
420 if (llvm::any_of(RD->ctors(), [](
const CXXConstructorDecl *Ctor) {
421 return Ctor->isCopyOrMoveConstructor() &&
422 (Ctor->isDeleted() || Ctor->getAccess() == AS_private);
427 InitRange = SourceRange(
428 New->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
429 New->getInitializer()->getSourceRange().getEnd());
431 Diag << FixItHint::CreateRemoval(
432 CharSourceRange::getCharRange(NewStart, InitRange.getBegin()));
433 Diag << FixItHint::CreateRemoval(
434 SourceRange(InitRange.getEnd().getLocWithOffset(1), NewEnd));
441void MakeSmartPtrCheck::insertHeader(DiagnosticBuilder &Diag, FileID FD) {
442 if (MakeSmartPtrFunctionHeader.empty()) {
445 Diag << Inserter.createIncludeInsertion(FD, MakeSmartPtrFunctionHeader);
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
virtual SmartPtrTypeMatcher getSmartPointerTypeMatcher() const =0
Returns matcher that match with different smart pointer types.
static const char PointerType[]
MakeSmartPtrCheck(StringRef Name, ClangTidyContext *Context, StringRef MakeSmartPtrFunctionName)
void check(const ast_matchers::MatchFinder::MatchResult &Result) final
bool isLanguageVersionSupported(const LangOptions &LangOpts) const override
Returns whether the C++ version is compatible with current check.
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
void registerMatchers(ast_matchers::MatchFinder *Finder) final
static std::string getNewExprName(const CXXNewExpr *NewExpr, const SourceManager &SM, const LangOptions &Lang)
static constexpr char ResetCall[]
static constexpr char NewExpression[]
static constexpr char DirectVar[]
static constexpr char ConstructorCall[]
bool isTriviallyDefaultConstructible(QualType Type, const ASTContext &Context)
Returns true if Type is trivially default constructible.
llvm::StringMap< ClangTidyValue > OptionMap