blob: bc255aaa35cdf83e78bde70c4a12a4853fa3068a [file] [log] [blame]
Benjamin Kramer190e2cf2014-07-08 14:32:17 +00001//===--- TwineLocalCheck.cpp - clang-tidy ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "TwineLocalCheck.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchers.h"
13#include "clang/Lex/Lexer.h"
Benjamin Kramer190e2cf2014-07-08 14:32:17 +000014
15using namespace clang::ast_matchers;
16
17namespace clang {
18namespace tidy {
19
20TwineLocalCheck::TwineLocalCheck() {}
21
22void TwineLocalCheck::registerMatchers(MatchFinder *Finder) {
23 auto TwineType =
24 qualType(hasDeclaration(recordDecl(hasName("::llvm::Twine"))));
25 Finder->addMatcher(varDecl(hasType(TwineType)).bind("variable"), this);
26}
27
28void TwineLocalCheck::check(const MatchFinder::MatchResult &Result) {
29 const VarDecl *VD = Result.Nodes.getNodeAs<VarDecl>("variable");
30 auto Diag = diag(VD->getLocation(),
Benjamin Krameree587212014-07-08 15:41:20 +000031 "twine variables are prone to use-after-free bugs");
Benjamin Kramer190e2cf2014-07-08 14:32:17 +000032
33 // If this VarDecl has an initializer try to fix it.
34 if (VD->hasInit()) {
35 // Peel away implicit constructors and casts so we can see the actual type
36 // of the initializer.
37 const Expr *C = VD->getInit();
38 while (isa<CXXConstructExpr>(C))
39 C = cast<CXXConstructExpr>(C)->getArg(0)->IgnoreParenImpCasts();
40
41 SourceRange TypeRange =
42 VD->getTypeSourceInfo()->getTypeLoc().getSourceRange();
43
44 // A real Twine, turn it into a std::string.
45 if (VD->getType()->getCanonicalTypeUnqualified() ==
46 C->getType()->getCanonicalTypeUnqualified()) {
47 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
48 VD->getInit()->getLocEnd(), 0, *Result.SourceManager,
49 Result.Context->getLangOpts());
50 Diag << FixItHint::CreateReplacement(TypeRange, "std::string")
51 << FixItHint::CreateInsertion(VD->getInit()->getLocStart(), "(")
52 << FixItHint::CreateInsertion(EndLoc, ").str()");
53 } else {
54 // Just an implicit conversion. Insert the real type.
55 Diag << FixItHint::CreateReplacement(
56 TypeRange,
57 C->getType().getAsString(Result.Context->getPrintingPolicy()));
58 }
59 }
60}
61
62} // namespace tidy
63} // namespace clang