clang-tools 22.0.0git
StringIntegerAssignmentCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/Lex/Lexer.h"
13
14using namespace clang::ast_matchers;
15
16namespace clang::tidy::bugprone {
17
19 Finder->addMatcher(
20 cxxOperatorCallExpr(
21 hasAnyOverloadedOperatorName("=", "+="),
22 callee(cxxMethodDecl(ofClass(classTemplateSpecializationDecl(
23 hasName("::std::basic_string"),
24 hasTemplateArgument(0, refersToType(hasCanonicalType(
25 qualType().bind("type")))))))),
26 hasArgument(
27 1,
28 ignoringImpCasts(
29 expr(hasType(isInteger()), unless(hasType(isAnyCharacter())),
30 // Ignore calls to tolower/toupper (see PR27723).
31 unless(callExpr(callee(functionDecl(
32 hasAnyName("tolower", "std::tolower", "toupper",
33 "std::toupper"))))),
34 // Do not warn if assigning e.g. `CodePoint` to
35 // `basic_string<CodePoint>`
36 unless(hasType(qualType(
37 hasCanonicalType(equalsBoundNode("type"))))))
38 .bind("expr"))),
39 unless(isInTemplateInstantiation())),
40 this);
41}
42
43namespace {
44
45class CharExpressionDetector {
46public:
47 CharExpressionDetector(QualType CharType, const ASTContext &Ctx)
48 : CharType(CharType), Ctx(Ctx) {}
49
50 bool isLikelyCharExpression(const Expr *E) const {
51 if (isCharTyped(E))
52 return true;
53
54 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
55 const auto *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
56 const auto *RHS = BinOp->getRHS()->IgnoreParenImpCasts();
57 // Handle both directions, e.g. `'a' + (i % 26)` and `(i % 26) + 'a'`.
58 if (BinOp->isAdditiveOp() || BinOp->isBitwiseOp())
59 return handleBinaryOp(BinOp->getOpcode(), LHS, RHS) ||
60 handleBinaryOp(BinOp->getOpcode(), RHS, LHS);
61 // Except in the case of '%'.
62 if (BinOp->getOpcode() == BO_Rem)
63 return handleBinaryOp(BinOp->getOpcode(), LHS, RHS);
64 return false;
65 }
66
67 // Ternary where at least one branch is a likely char expression, e.g.
68 // i < 265 ? i : ' '
69 if (const auto *CondOp = dyn_cast<AbstractConditionalOperator>(E))
70 return isLikelyCharExpression(
71 CondOp->getFalseExpr()->IgnoreParenImpCasts()) ||
72 isLikelyCharExpression(
73 CondOp->getTrueExpr()->IgnoreParenImpCasts());
74 return false;
75 }
76
77private:
78 bool handleBinaryOp(clang::BinaryOperatorKind Opcode, const Expr *const LHS,
79 const Expr *const RHS) const {
80 // <char_expr> <op> <char_expr> (c++ integer promotion rules make this an
81 // int), e.g.
82 // 'a' + c
83 if (isCharTyped(LHS) && isCharTyped(RHS))
84 return true;
85
86 // <expr> & <char_valued_constant> or <expr> % <char_valued_constant>, e.g.
87 // i & 0xff
88 if ((Opcode == BO_And || Opcode == BO_Rem) && isCharValuedConstant(RHS))
89 return true;
90
91 // <char_expr> | <char_valued_constant>, e.g.
92 // c | 0x80
93 if (Opcode == BO_Or && isCharTyped(LHS) && isCharValuedConstant(RHS))
94 return true;
95
96 // <char_constant> + <likely_char_expr>, e.g.
97 // 'a' + (i % 26)
98 if (Opcode == BO_Add)
99 return isCharConstant(LHS) && isLikelyCharExpression(RHS);
100
101 return false;
102 }
103
104 // Returns true if `E` is an character constant.
105 bool isCharConstant(const Expr *E) const {
106 return isCharTyped(E) && isCharValuedConstant(E);
107 };
108
109 // Returns true if `E` is an integer constant which fits in `CharType`.
110 bool isCharValuedConstant(const Expr *E) const {
111 if (E->isInstantiationDependent())
112 return false;
113 Expr::EvalResult EvalResult;
114 if (!E->EvaluateAsInt(EvalResult, Ctx, Expr::SE_AllowSideEffects))
115 return false;
116 return EvalResult.Val.getInt().getActiveBits() <= Ctx.getTypeSize(CharType);
117 };
118
119 // Returns true if `E` has the right character type.
120 bool isCharTyped(const Expr *E) const {
121 return E->getType().getCanonicalType().getTypePtr() ==
122 CharType.getTypePtr();
123 };
124
125 const QualType CharType;
126 const ASTContext &Ctx;
127};
128
129} // namespace
130
132 const MatchFinder::MatchResult &Result) {
133 const auto *Argument = Result.Nodes.getNodeAs<Expr>("expr");
134 const auto CharType =
135 Result.Nodes.getNodeAs<QualType>("type")->getCanonicalType();
136 const SourceLocation Loc = Argument->getBeginLoc();
137
138 // Try to detect a few common expressions to reduce false positives.
139 if (CharExpressionDetector(CharType, *Result.Context)
140 .isLikelyCharExpression(Argument))
141 return;
142
143 auto Diag =
144 diag(Loc, "an integer is interpreted as a character code when assigning "
145 "it to a string; if this is intended, cast the integer to the "
146 "appropriate character type; if you want a string "
147 "representation, use the appropriate conversion facility");
148
149 if (Loc.isMacroID())
150 return;
151
152 const bool IsWideCharType = CharType->isWideCharType();
153 if (!CharType->isCharType() && !IsWideCharType)
154 return;
155 bool IsOneDigit = false;
156 bool IsLiteral = false;
157 if (const auto *Literal = dyn_cast<IntegerLiteral>(Argument)) {
158 IsOneDigit = Literal->getValue().getLimitedValue() < 10;
159 IsLiteral = true;
160 }
161
162 const SourceLocation EndLoc = Lexer::getLocForEndOfToken(
163 Argument->getEndLoc(), 0, *Result.SourceManager, getLangOpts());
164 if (IsOneDigit) {
165 Diag << FixItHint::CreateInsertion(Loc, IsWideCharType ? "L'" : "'")
166 << FixItHint::CreateInsertion(EndLoc, "'");
167 return;
168 }
169 if (IsLiteral) {
170 Diag << FixItHint::CreateInsertion(Loc, IsWideCharType ? "L\"" : "\"")
171 << FixItHint::CreateInsertion(EndLoc, "\"");
172 return;
173 }
174
175 if (getLangOpts().CPlusPlus11) {
176 Diag << FixItHint::CreateInsertion(Loc, IsWideCharType ? "std::to_wstring("
177 : "std::to_string(")
178 << FixItHint::CreateInsertion(EndLoc, ")");
179 }
180}
181
182} // namespace clang::tidy::bugprone
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override