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 const StringRef WrittenName = Lexer::getSourceText(
28 CharSourceRange::getTokenRange(
29 NewExpr->getAllocatedTypeSourceInfo()->getTypeLoc().getSourceRange()),
31 if (NewExpr->isArray())
32 return (WrittenName +
"[]").str();
33 return WrittenName.str();
39 StringRef MakeSmartPtrFunctionName)
41 Inserter(Options.getLocalOrGlobal(
"IncludeStyle",
42 utils::IncludeSorter::IS_LLVM),
43 areDiagsSelfContained()),
44 MakeSmartPtrFunctionHeader(
45 Options.get(
"MakeSmartPtrFunctionHeader",
"<memory>")),
46 MakeSmartPtrFunctionName(
47 Options.get(
"MakeSmartPtrFunction", MakeSmartPtrFunctionName)),
48 IgnoreMacros(Options.get(
"IgnoreMacros", true)),
49 IgnoreDefaultInitialization(
50 Options.get(
"IgnoreDefaultInitialization", true)) {}
53 Options.store(Opts,
"IncludeStyle", Inserter.getStyle());
54 Options.store(Opts,
"MakeSmartPtrFunctionHeader", MakeSmartPtrFunctionHeader);
55 Options.store(Opts,
"MakeSmartPtrFunction", MakeSmartPtrFunctionName);
56 Options.store(Opts,
"IgnoreMacros", IgnoreMacros);
57 Options.store(Opts,
"IgnoreDefaultInitialization",
58 IgnoreDefaultInitialization);
62 const LangOptions &LangOpts)
const {
63 return LangOpts.CPlusPlus11;
68 Preprocessor *ModuleExpanderPP) {
69 Inserter.registerPreprocessor(PP);
75 auto CanCallCtor = unless(has(ignoringImpCasts(
76 cxxConstructExpr(hasDeclaration(decl(unless(isPublic())))))));
78 auto IsPlacement = hasAnyPlacementArg(anything());
83 anyOf(hasParent(cxxBindTemporaryExpr()),
87 0, cxxNewExpr(hasType(pointsTo(qualType(hasCanonicalType(
89 CanCallCtor, unless(IsPlacement))
91 unless(isInTemplateInstantiation()))
99 unless(isInTemplateInstantiation()),
100 hasArgument(0, cxxNewExpr(CanCallCtor, unless(IsPlacement))
102 callee(cxxMethodDecl(hasName(
"reset"))),
104 on(ignoringImplicit(anyOf(
116 SourceManager &SM = *Result.SourceManager;
117 const auto *Construct =
119 const auto *DVar = Result.Nodes.getNodeAs<VarDecl>(
DirectVar);
120 const auto *Reset = Result.Nodes.getNodeAs<CXXMemberCallExpr>(
ResetCall);
121 const auto *Type = Result.Nodes.getNodeAs<QualType>(
PointerType);
122 const auto *New = Result.Nodes.getNodeAs<CXXNewExpr>(
NewExpression);
125 if (New->getType()->getPointeeType()->getContainedAutoType())
136 const bool Initializes = New->hasInitializer() ||
138 New->getAllocatedType(), *Result.Context);
139 if (!Initializes && IgnoreDefaultInitialization)
142 checkConstruct(SM, Result.Context, Construct, DVar, Type, New);
144 checkReset(SM, Result.Context, Reset, New);
147void MakeSmartPtrCheck::checkConstruct(SourceManager &SM, ASTContext *Ctx,
148 const CXXConstructExpr *Construct,
150 const QualType *Type,
151 const CXXNewExpr *New) {
152 const SourceLocation ConstructCallStart = Construct->getExprLoc();
153 const bool InMacro = ConstructCallStart.isMacroID();
155 if (InMacro && IgnoreMacros)
158 bool Invalid =
false;
159 const StringRef ExprStr = Lexer::getSourceText(
160 CharSourceRange::getCharRange(
161 ConstructCallStart, Construct->getParenOrBraceRange().getBegin()),
162 SM, getLangOpts(), &Invalid);
166 auto Diag = diag(ConstructCallStart,
"use %0 instead")
167 << MakeSmartPtrFunctionName;
173 if (!replaceNew(Diag, New, SM, Ctx))
177 const size_t LAngle = ExprStr.find(
'<');
178 SourceLocation ConstructCallEnd;
179 if (LAngle == StringRef::npos) {
182 ConstructCallEnd = ConstructCallStart.getLocWithOffset(ExprStr.size());
183 Diag << FixItHint::CreateInsertion(
184 ConstructCallEnd,
"<" +
getNewExprName(New, SM, getLangOpts()) +
">");
186 ConstructCallEnd = ConstructCallStart.getLocWithOffset(LAngle);
189 std::string FinalMakeSmartPtrFunctionName = MakeSmartPtrFunctionName.str();
191 FinalMakeSmartPtrFunctionName =
192 ExprStr.str() +
" = " + MakeSmartPtrFunctionName.str();
194 Diag << FixItHint::CreateReplacement(
195 CharSourceRange::getCharRange(ConstructCallStart, ConstructCallEnd),
196 FinalMakeSmartPtrFunctionName);
200 if (Construct->isListInitialization()) {
201 const SourceRange BraceRange = Construct->getParenOrBraceRange();
202 Diag << FixItHint::CreateReplacement(
203 CharSourceRange::getCharRange(
204 BraceRange.getBegin(), BraceRange.getBegin().getLocWithOffset(1)),
206 Diag << FixItHint::CreateReplacement(
207 CharSourceRange::getCharRange(BraceRange.getEnd(),
208 BraceRange.getEnd().getLocWithOffset(1)),
212 insertHeader(Diag, SM.getFileID(ConstructCallStart));
215void MakeSmartPtrCheck::checkReset(SourceManager &SM, ASTContext *Ctx,
216 const CXXMemberCallExpr *Reset,
217 const CXXNewExpr *New) {
218 const auto *Expr = cast<MemberExpr>(Reset->getCallee());
219 const SourceLocation OperatorLoc = Expr->getOperatorLoc();
220 const SourceLocation ResetCallStart = Reset->getExprLoc();
221 const SourceLocation ExprStart = Expr->getBeginLoc();
222 const SourceLocation ExprEnd =
223 Lexer::getLocForEndOfToken(Expr->getEndLoc(), 0, SM, getLangOpts());
225 const bool InMacro = ExprStart.isMacroID();
227 if (InMacro && IgnoreMacros)
233 if (OperatorLoc.isInvalid())
236 auto Diag = diag(ResetCallStart,
"use %0 instead")
237 << MakeSmartPtrFunctionName;
243 if (!replaceNew(Diag, New, SM, Ctx))
246 Diag << FixItHint::CreateReplacement(
247 CharSourceRange::getCharRange(OperatorLoc, ExprEnd),
248 (llvm::Twine(
" = ") + MakeSmartPtrFunctionName +
"<" +
253 Diag << FixItHint::CreateInsertion(ExprStart,
"*");
255 insertHeader(Diag, SM.getFileID(OperatorLoc));
258bool MakeSmartPtrCheck::replaceNew(DiagnosticBuilder &Diag,
259 const CXXNewExpr *New, SourceManager &SM,
261 auto SkipParensParents = [&](
const Expr *E) {
262 const TraversalKindScope RAII(*Ctx, TK_AsIs);
264 for (
const Expr *OldE =
nullptr; E != OldE;) {
266 for (
const auto &Node : Ctx->getParents(*E)) {
267 if (
const Expr *Parent = Node.get<ParenExpr>()) {
276 const SourceRange NewRange = SkipParensParents(New)->getSourceRange();
277 const SourceLocation NewStart = NewRange.getBegin();
278 const SourceLocation NewEnd = NewRange.getEnd();
281 if (NewStart.isInvalid() || NewEnd.isInvalid())
284 std::string ArraySizeExpr;
285 if (
const auto *ArraySize = New->getArraySize().value_or(
nullptr)) {
286 ArraySizeExpr = Lexer::getSourceText(CharSourceRange::getTokenRange(
287 ArraySize->getSourceRange()),
297 auto HasListIntializedArgument = [](
const CXXConstructExpr *CE) {
298 for (
const auto *Arg : CE->arguments()) {
299 Arg = Arg->IgnoreImplicit();
301 if (isa<CXXStdInitializerListExpr>(Arg) || isa<InitListExpr>(Arg))
305 if (
const auto *CEArg = dyn_cast<CXXConstructExpr>(Arg)) {
309 if (CEArg->isElidable()) {
310 if (
const auto *TempExp = CEArg->getArg(0)) {
311 if (
const auto *UnwrappedCE =
312 dyn_cast<CXXConstructExpr>(TempExp->IgnoreImplicit()))
316 if (CEArg->isStdInitListInitialization())
322 switch (New->getInitializationStyle()) {
323 case CXXNewInitializationStyle::None: {
324 if (ArraySizeExpr.empty()) {
325 Diag << FixItHint::CreateRemoval(SourceRange(NewStart, NewEnd));
329 Diag << FixItHint::CreateReplacement(SourceRange(NewStart, NewEnd),
334 case CXXNewInitializationStyle::Parens: {
352 if (
const auto *CE = New->getConstructExpr()) {
353 if (HasListIntializedArgument(CE))
356 if (ArraySizeExpr.empty()) {
357 const SourceRange InitRange = New->getDirectInitRange();
358 Diag << FixItHint::CreateRemoval(
359 SourceRange(NewStart, InitRange.getBegin()));
360 Diag << FixItHint::CreateRemoval(SourceRange(InitRange.getEnd(), NewEnd));
365 Diag << FixItHint::CreateReplacement(SourceRange(NewStart, NewEnd),
370 case CXXNewInitializationStyle::Braces: {
372 SourceRange InitRange;
373 if (
const auto *NewConstruct = New->getConstructExpr()) {
374 if (NewConstruct->isStdInitListInitialization() ||
375 HasListIntializedArgument(NewConstruct)) {
398 InitRange = SourceRange(
399 NewConstruct->getParenOrBraceRange().getBegin().getLocWithOffset(1),
400 NewConstruct->getParenOrBraceRange().getEnd().getLocWithOffset(-1));
411 if (
const CXXRecordDecl *RD = New->getType()->getPointeeCXXRecordDecl()) {
412 if (llvm::any_of(RD->ctors(), [](
const CXXConstructorDecl *Ctor) {
413 return Ctor->isCopyOrMoveConstructor() &&
414 (Ctor->isDeleted() || Ctor->getAccess() == AS_private);
419 InitRange = SourceRange(
420 New->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
421 New->getInitializer()->getSourceRange().getEnd());
423 Diag << FixItHint::CreateRemoval(
424 CharSourceRange::getCharRange(NewStart, InitRange.getBegin()));
425 Diag << FixItHint::CreateRemoval(
426 SourceRange(InitRange.getEnd().getLocWithOffset(1), NewEnd));
433void MakeSmartPtrCheck::insertHeader(DiagnosticBuilder &Diag, FileID FD) {
434 if (MakeSmartPtrFunctionHeader.empty())
436 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