clang-tools 3.8.0

- Main Page
- Namespaces
- Classes
- Files

- File List
- File Members

TwineLocalCheck.cpp
Go to the documentation of this file.
1 //===--- 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"
14
15 using namespace clang::ast_matchers;
16
17 namespace clang {
18 namespace tidy {
19 namespace llvm {
20
21 void TwineLocalCheck::registerMatchers(MatchFinder *Finder) {
22 auto TwineType =
23 qualType(hasDeclaration(recordDecl(hasName("::llvm::Twine"))));
24 Finder->addMatcher(varDecl(hasType(TwineType)).bind("variable"), this);
25 }
26
27 void TwineLocalCheck::check(const MatchFinder::MatchResult &Result) {
28 const VarDecl *VD = Result.Nodes.getNodeAs<VarDecl>("variable");
29 auto Diag = diag(VD->getLocation(),
30 "twine variables are prone to use-after-free bugs");
31
32 // If this VarDecl has an initializer try to fix it.
33 if (VD->hasInit()) {
34 // Peel away implicit constructors and casts so we can see the actual type
35 // of the initializer.
36 const Expr *C = VD->getInit();
37 while (isa<CXXConstructExpr>(C))
38 C = cast<CXXConstructExpr>(C)->getArg(0)->IgnoreParenImpCasts();
39
40 SourceRange TypeRange =
41 VD->getTypeSourceInfo()->getTypeLoc().getSourceRange();
42
43 // A real Twine, turn it into a std::string.
44 if (VD->getType()->getCanonicalTypeUnqualified() ==
45 C->getType()->getCanonicalTypeUnqualified()) {
46 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
47 VD->getInit()->getLocEnd(), 0, *Result.SourceManager,
48 Result.Context->getLangOpts());
49 Diag << FixItHint::CreateReplacement(TypeRange, "std::string")
50 << FixItHint::CreateInsertion(VD->getInit()->getLocStart(), "(")
51 << FixItHint::CreateInsertion(EndLoc, ").str()");
52 } else {
53 // Just an implicit conversion. Insert the real type.
54 Diag << FixItHint::CreateReplacement(
55 TypeRange,
56 C->getType().getAsString(Result.Context->getPrintingPolicy()));
57 }
58 }
59 }
60
61 } // namespace llvm
62 } // namespace tidy
63 } // namespace clang
Finder
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:188
TwineLocalCheck.h
Result
const NamedDecl * Result
Definition: USRFinder.cpp:121