TwineLocalCheck.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //===--- TwineLocalCheck.cpp - clang-tidy ---------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "TwineLocalCheck.h"
  9. #include "clang/AST/ASTContext.h"
  10. #include "clang/ASTMatchers/ASTMatchers.h"
  11. #include "clang/Lex/Lexer.h"
  12. using namespace clang::ast_matchers;
  13. namespace clang::tidy::llvm_check {
  14. void TwineLocalCheck::registerMatchers(MatchFinder *Finder) {
  15. auto TwineType =
  16. qualType(hasDeclaration(cxxRecordDecl(hasName("::llvm::Twine"))));
  17. Finder->addMatcher(
  18. varDecl(unless(parmVarDecl()), hasType(TwineType)).bind("variable"),
  19. this);
  20. }
  21. void TwineLocalCheck::check(const MatchFinder::MatchResult &Result) {
  22. const auto *VD = Result.Nodes.getNodeAs<VarDecl>("variable");
  23. auto Diag = diag(VD->getLocation(),
  24. "twine variables are prone to use-after-free bugs");
  25. // If this VarDecl has an initializer try to fix it.
  26. if (VD->hasInit()) {
  27. // Peel away implicit constructors and casts so we can see the actual type
  28. // of the initializer.
  29. const Expr *C = VD->getInit()->IgnoreImplicit();
  30. while (isa<CXXConstructExpr>(C)) {
  31. if (cast<CXXConstructExpr>(C)->getNumArgs() == 0)
  32. break;
  33. C = cast<CXXConstructExpr>(C)->getArg(0)->IgnoreParenImpCasts();
  34. }
  35. SourceRange TypeRange =
  36. VD->getTypeSourceInfo()->getTypeLoc().getSourceRange();
  37. // A real Twine, turn it into a std::string.
  38. if (VD->getType()->getCanonicalTypeUnqualified() ==
  39. C->getType()->getCanonicalTypeUnqualified()) {
  40. SourceLocation EndLoc = Lexer::getLocForEndOfToken(
  41. VD->getInit()->getEndLoc(), 0, *Result.SourceManager, getLangOpts());
  42. Diag << FixItHint::CreateReplacement(TypeRange, "std::string")
  43. << FixItHint::CreateInsertion(VD->getInit()->getBeginLoc(), "(")
  44. << FixItHint::CreateInsertion(EndLoc, ").str()");
  45. } else {
  46. // Just an implicit conversion. Insert the real type.
  47. Diag << FixItHint::CreateReplacement(
  48. TypeRange,
  49. C->getType().getAsString(Result.Context->getPrintingPolicy()));
  50. }
  51. }
  52. }
  53. } // namespace clang::tidy::llvm_check