11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Lex/Lexer.h"
15 using namespace clang::ast_matchers;
20 void StringIntegerAssignmentCheck::registerMatchers(MatchFinder *
Finder) {
21 if (!getLangOpts().CPlusPlus)
25 anyOf(hasOverloadedOperatorName(
"="),
26 hasOverloadedOperatorName(
"+=")),
27 callee(cxxMethodDecl(ofClass(classTemplateSpecializationDecl(
28 hasName(
"::std::basic_string"),
29 hasTemplateArgument(0, refersToType(qualType().bind(
"type"))))))),
31 ignoringImpCasts(expr(hasType(isInteger()),
32 unless(hasType(isAnyCharacter())))
34 unless(isInTemplateInstantiation())),
38 void StringIntegerAssignmentCheck::check(
39 const MatchFinder::MatchResult &
Result) {
40 const auto *
Argument = Result.Nodes.getNodeAs<Expr>(
"expr");
44 diag(Loc,
"an integer is interpreted as a character code when assigning "
45 "it to a string; if this is intended, cast the integer to the "
46 "appropriate character type; if you want a string "
47 "representation, use the appropriate conversion facility");
52 auto CharType = *Result.Nodes.getNodeAs<QualType>(
"type");
53 bool IsWideCharType = CharType->isWideCharType();
54 if (!CharType->isCharType() && !IsWideCharType)
56 bool IsOneDigit =
false;
57 bool IsLiteral =
false;
58 if (
const auto *Literal = dyn_cast<IntegerLiteral>(
Argument)) {
59 IsOneDigit = Literal->getValue().getLimitedValue() < 10;
63 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
64 Argument->getLocEnd(), 0, *Result.SourceManager,
65 Result.Context->getLangOpts());
67 Diag << FixItHint::CreateInsertion(Loc, IsWideCharType ?
"L'" :
"'")
68 << FixItHint::CreateInsertion(EndLoc,
"'");
72 Diag << FixItHint::CreateInsertion(Loc, IsWideCharType ?
"L\"" :
"\"")
73 << FixItHint::CreateInsertion(EndLoc,
"\"");
77 if (getLangOpts().CPlusPlus11) {
78 Diag << FixItHint::CreateInsertion(Loc, IsWideCharType ?
"std::to_wstring("
80 << FixItHint::CreateInsertion(EndLoc,
")");
SourceLocation Loc
'#' location in the include directive
This class represents one callback function argument by name and value.
std::unique_ptr< ast_matchers::MatchFinder > Finder