10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchers.h"
12#include "clang/Lex/Lexer.h"
20 qualType(hasDeclaration(cxxRecordDecl(hasName(
"::llvm::Twine"))));
22 varDecl(unless(parmVarDecl()), hasType(TwineType)).bind(
"variable"),
27 const auto *VD = Result.Nodes.getNodeAs<VarDecl>(
"variable");
28 auto Diag =
diag(VD->getLocation(),
29 "twine variables are prone to use-after-free bugs");
35 const Expr *
C = VD->getInit()->IgnoreImplicit();
37 while (isa<CXXConstructExpr>(
C)) {
38 if (cast<CXXConstructExpr>(
C)->getNumArgs() == 0)
40 C = cast<CXXConstructExpr>(
C)->getArg(0)->IgnoreParenImpCasts();
43 SourceRange TypeRange =
44 VD->getTypeSourceInfo()->getTypeLoc().getSourceRange();
47 if (VD->getType()->getCanonicalTypeUnqualified() ==
48 C->getType()->getCanonicalTypeUnqualified()) {
49 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
50 VD->getInit()->getEndLoc(), 0, *Result.SourceManager,
getLangOpts());
51 Diag << FixItHint::CreateReplacement(TypeRange,
"std::string")
52 << FixItHint::CreateInsertion(VD->getInit()->getBeginLoc(),
"(")
53 << FixItHint::CreateInsertion(EndLoc,
").str()");
56 Diag << FixItHint::CreateReplacement(
58 C->getType().getAsString(Result.Context->getPrintingPolicy()));
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
const LangOptions & getLangOpts() const
Returns the language options from the context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.