11 #include "clang/AST/ASTContext.h" 12 #include "clang/ASTMatchers/ASTMatchFinder.h" 13 #include "clang/Lex/Lexer.h" 14 #include "clang/Tooling/FixIt.h" 21 namespace readability {
26 SourceManager &SM = Finder->getASTContext().getSourceManager();
27 SourceLocation
Loc = Node.getBeginLoc();
28 return SM.isMacroBodyExpansion(Loc) || SM.isMacroArgExpansion(Loc);
31 bool isNULLMacroExpansion(
const Stmt *Statement, ASTContext &Context) {
32 SourceManager &SM = Context.getSourceManager();
33 const LangOptions &LO = Context.getLangOpts();
34 SourceLocation Loc = Statement->getBeginLoc();
35 return SM.isMacroBodyExpansion(Loc) &&
36 Lexer::getImmediateMacroName(Loc, SM, LO) ==
"NULL";
40 return isNULLMacroExpansion(&Node, Finder->getASTContext());
43 StringRef getZeroLiteralToCompareWithForType(CastKind CastExprKind,
45 ASTContext &Context) {
46 switch (CastExprKind) {
47 case CK_IntegralToBoolean:
48 return Type->isUnsignedIntegerType() ?
"0u" :
"0";
50 case CK_FloatingToBoolean:
51 return Context.hasSameType(Type, Context.FloatTy) ?
"0.0f" :
"0.0";
53 case CK_PointerToBoolean:
54 case CK_MemberPointerToBoolean:
55 return Context.getLangOpts().CPlusPlus11 ?
"nullptr" :
"0";
58 llvm_unreachable(
"Unexpected cast kind");
62 bool isUnaryLogicalNotOperator(
const Stmt *Statement) {
63 const auto *UnaryOperatorExpr = dyn_cast<UnaryOperator>(Statement);
64 return UnaryOperatorExpr && UnaryOperatorExpr->getOpcode() == UO_LNot;
67 bool areParensNeededForOverloadedOperator(OverloadedOperatorKind OperatorKind) {
68 switch (OperatorKind) {
84 bool areParensNeededForStatement(
const Stmt *Statement) {
85 if (
const auto *OperatorCall = dyn_cast<CXXOperatorCallExpr>(Statement)) {
86 return areParensNeededForOverloadedOperator(OperatorCall->getOperator());
89 return isa<BinaryOperator>(Statement) || isa<UnaryOperator>(Statement);
92 void fixGenericExprCastToBool(DiagnosticBuilder &Diag,
93 const ImplicitCastExpr *Cast,
const Stmt *Parent,
94 ASTContext &Context) {
97 bool InvertComparison =
98 Parent !=
nullptr && isUnaryLogicalNotOperator(Parent);
99 if (InvertComparison) {
100 SourceLocation ParentStartLoc = Parent->getBeginLoc();
101 SourceLocation ParentEndLoc =
102 cast<UnaryOperator>(Parent)->getSubExpr()->getBeginLoc();
103 Diag << FixItHint::CreateRemoval(
104 CharSourceRange::getCharRange(ParentStartLoc, ParentEndLoc));
106 Parent = Context.getParents(*Parent)[0].get<Stmt>();
109 const Expr *SubExpr = Cast->getSubExpr();
111 bool NeedInnerParens = areParensNeededForStatement(SubExpr);
112 bool NeedOuterParens =
113 Parent !=
nullptr && areParensNeededForStatement(Parent);
115 std::string StartLocInsertion;
117 if (NeedOuterParens) {
118 StartLocInsertion +=
"(";
120 if (NeedInnerParens) {
121 StartLocInsertion +=
"(";
124 if (!StartLocInsertion.empty()) {
125 Diag << FixItHint::CreateInsertion(Cast->getBeginLoc(), StartLocInsertion);
128 std::string EndLocInsertion;
130 if (NeedInnerParens) {
131 EndLocInsertion +=
")";
134 if (InvertComparison) {
135 EndLocInsertion +=
" == ";
137 EndLocInsertion +=
" != ";
140 EndLocInsertion += getZeroLiteralToCompareWithForType(
141 Cast->getCastKind(), SubExpr->getType(), Context);
143 if (NeedOuterParens) {
144 EndLocInsertion +=
")";
147 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
148 Cast->getEndLoc(), 0, Context.getSourceManager(), Context.getLangOpts());
149 Diag << FixItHint::CreateInsertion(EndLoc, EndLocInsertion);
152 StringRef getEquivalentBoolLiteralForExpr(
const Expr *Expression,
153 ASTContext &Context) {
154 if (isNULLMacroExpansion(Expression, Context)) {
158 if (
const auto *IntLit = dyn_cast<IntegerLiteral>(Expression)) {
159 return (IntLit->getValue() == 0) ?
"false" :
"true";
162 if (
const auto *FloatLit = dyn_cast<FloatingLiteral>(Expression)) {
163 llvm::APFloat FloatLitAbsValue = FloatLit->getValue();
164 FloatLitAbsValue.clearSign();
165 return (FloatLitAbsValue.bitcastToAPInt() == 0) ?
"false" :
"true";
168 if (
const auto *CharLit = dyn_cast<CharacterLiteral>(Expression)) {
169 return (CharLit->getValue() == 0) ?
"false" :
"true";
172 if (isa<StringLiteral>(Expression->IgnoreCasts())) {
179 void fixGenericExprCastFromBool(DiagnosticBuilder &Diag,
180 const ImplicitCastExpr *Cast,
181 ASTContext &Context, StringRef OtherType) {
182 const Expr *SubExpr = Cast->getSubExpr();
183 bool NeedParens = !isa<ParenExpr>(SubExpr);
185 Diag << FixItHint::CreateInsertion(
187 (Twine(
"static_cast<") + OtherType +
">" + (NeedParens ?
"(" :
""))
191 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
192 Cast->getEndLoc(), 0, Context.getSourceManager(),
193 Context.getLangOpts());
195 Diag << FixItHint::CreateInsertion(EndLoc,
")");
199 StringRef getEquivalentForBoolLiteral(
const CXXBoolLiteralExpr *BoolLiteral,
200 QualType DestType, ASTContext &Context) {
202 if (!Context.getLangOpts().CPlusPlus11 &&
203 (DestType->isPointerType() || DestType->isMemberPointerType()) &&
204 BoolLiteral->getValue() ==
false) {
208 if (DestType->isFloatingType()) {
209 if (Context.hasSameType(DestType, Context.FloatTy)) {
210 return BoolLiteral->getValue() ?
"1.0f" :
"0.0f";
212 return BoolLiteral->getValue() ?
"1.0" :
"0.0";
215 if (DestType->isUnsignedIntegerType()) {
216 return BoolLiteral->getValue() ?
"1u" :
"0u";
218 return BoolLiteral->getValue() ?
"1" :
"0";
221 bool isCastAllowedInCondition(
const ImplicitCastExpr *Cast,
222 ASTContext &Context) {
223 std::queue<const Stmt *> Q;
226 for (
const auto &N : Context.getParents(*Q.front())) {
227 const Stmt *S = N.get<Stmt>();
230 if (isa<IfStmt>(S) || isa<ConditionalOperator>(S) || isa<ForStmt>(S) ||
231 isa<WhileStmt>(S) || isa<BinaryConditionalOperator>(S))
233 if (isa<ParenExpr>(S) || isa<ImplicitCastExpr>(S) ||
234 isUnaryLogicalNotOperator(S) ||
235 (isa<BinaryOperator>(S) && cast<BinaryOperator>(S)->isLogicalOp())) {
248 ImplicitBoolConversionCheck::ImplicitBoolConversionCheck(
251 AllowIntegerConditions(Options.get(
"AllowIntegerConditions", false)),
252 AllowPointerConditions(Options.get(
"AllowPointerConditions", false)) {}
256 Options.
store(Opts,
"AllowIntegerConditions", AllowIntegerConditions);
257 Options.
store(Opts,
"AllowPointerConditions", AllowPointerConditions);
267 auto exceptionCases =
268 expr(anyOf(allOf(isMacroExpansion(), unless(isNULLMacroExpansion())),
269 has(ignoringImplicit(memberExpr(hasDeclaration(fieldDecl(hasBitWidth(1)))))),
270 hasParent(explicitCastExpr())));
271 auto implicitCastFromBool = implicitCastExpr(
272 anyOf(hasCastKind(CK_IntegralCast), hasCastKind(CK_IntegralToFloating),
274 allOf(anyOf(hasCastKind(CK_NullToPointer),
275 hasCastKind(CK_NullToMemberPointer)),
276 hasSourceExpression(cxxBoolLiteral()))),
277 hasSourceExpression(expr(hasType(booleanType()))),
278 unless(exceptionCases));
280 binaryOperator(hasOperatorName(
"^"), hasLHS(implicitCastFromBool),
281 hasRHS(implicitCastFromBool));
284 anyOf(hasCastKind(CK_IntegralToBoolean),
285 hasCastKind(CK_FloatingToBoolean),
286 hasCastKind(CK_PointerToBoolean),
287 hasCastKind(CK_MemberPointerToBoolean)),
292 hasParent(stmt(anyOf(ifStmt(), whileStmt()), has(declStmt())))),
294 unless(exceptionCases), unless(has(boolXor)),
297 anyOf(hasParent(stmt().bind(
"parentStmt")), anything()),
298 unless(isInTemplateInstantiation()),
299 unless(hasAncestor(functionTemplateDecl())))
300 .bind(
"implicitCastToBool"),
303 auto boolComparison = binaryOperator(
304 anyOf(hasOperatorName(
"=="), hasOperatorName(
"!=")),
305 hasLHS(implicitCastFromBool), hasRHS(implicitCastFromBool));
306 auto boolOpAssignment =
307 binaryOperator(anyOf(hasOperatorName(
"|="), hasOperatorName(
"&=")),
308 hasLHS(expr(hasType(booleanType()))));
309 auto bitfieldAssignment = binaryOperator(
310 hasLHS(memberExpr(hasDeclaration(fieldDecl(hasBitWidth(1))))));
311 auto bitfieldConstruct = cxxConstructorDecl(hasDescendant(cxxCtorInitializer(
312 withInitializer(equalsBoundNode(
"implicitCastFromBool")),
313 forField(hasBitWidth(1)))));
316 implicitCastFromBool,
321 unless(hasParent(binaryOperator(anyOf(
322 boolComparison, boolXor, boolOpAssignment, bitfieldAssignment)))),
323 implicitCastExpr().bind(
"implicitCastFromBool"),
324 unless(hasParent(bitfieldConstruct)),
326 anyOf(hasParent(implicitCastExpr().bind(
"furtherImplicitCast")),
328 unless(isInTemplateInstantiation()),
329 unless(hasAncestor(functionTemplateDecl()))),
334 const MatchFinder::MatchResult &
Result) {
335 if (
const auto *CastToBool =
336 Result.Nodes.getNodeAs<ImplicitCastExpr>(
"implicitCastToBool")) {
337 const auto *Parent = Result.Nodes.getNodeAs<Stmt>(
"parentStmt");
338 return handleCastToBool(CastToBool, Parent, *Result.Context);
341 if (
const auto *CastFromBool =
342 Result.Nodes.getNodeAs<ImplicitCastExpr>(
"implicitCastFromBool")) {
343 const auto *NextImplicitCast =
344 Result.Nodes.getNodeAs<ImplicitCastExpr>(
"furtherImplicitCast");
345 return handleCastFromBool(CastFromBool, NextImplicitCast, *Result.Context);
349 void ImplicitBoolConversionCheck::handleCastToBool(
const ImplicitCastExpr *Cast,
351 ASTContext &Context) {
352 if (AllowPointerConditions &&
353 (Cast->getCastKind() == CK_PointerToBoolean ||
354 Cast->getCastKind() == CK_MemberPointerToBoolean) &&
355 isCastAllowedInCondition(Cast, Context)) {
359 if (AllowIntegerConditions && Cast->getCastKind() == CK_IntegralToBoolean &&
360 isCastAllowedInCondition(Cast, Context)) {
364 auto Diag =
diag(Cast->getBeginLoc(),
"implicit conversion %0 -> bool")
365 << Cast->getSubExpr()->getType();
367 StringRef EquivalentLiteral =
368 getEquivalentBoolLiteralForExpr(Cast->getSubExpr(), Context);
369 if (!EquivalentLiteral.empty()) {
370 Diag << tooling::fixit::createReplacement(*Cast, EquivalentLiteral);
372 fixGenericExprCastToBool(Diag, Cast, Parent, Context);
376 void ImplicitBoolConversionCheck::handleCastFromBool(
377 const ImplicitCastExpr *Cast,
const ImplicitCastExpr *NextImplicitCast,
378 ASTContext &Context) {
380 NextImplicitCast ? NextImplicitCast->getType() : Cast->getType();
381 auto Diag =
diag(Cast->getBeginLoc(),
"implicit conversion bool -> %0")
384 if (
const auto *BoolLiteral =
385 dyn_cast<CXXBoolLiteralExpr>(Cast->getSubExpr())) {
386 Diag << tooling::fixit::createReplacement(
387 *Cast, getEquivalentForBoolLiteral(BoolLiteral, DestType, Context));
389 fixGenericExprCastFromBool(Diag, Cast, Context, DestType.getAsString());
SourceLocation Loc
'#' location in the include directive
AST_MATCHER(BinaryOperator, isAssignmentOperator)
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
LangOptions getLangOpts() const
Returns the language options from the context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
Base class for all clang-tidy checks.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
static constexpr llvm::StringLiteral Name
std::map< std::string, std::string > OptionMap
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.