10 #include "clang/AST/ASTContext.h" 11 #include "clang/ASTMatchers/ASTMatchFinder.h" 12 #include "clang/Lex/Lexer.h" 13 #include "clang/Tooling/FixIt.h" 20 namespace readability {
25 SourceManager &SM = Finder->getASTContext().getSourceManager();
26 SourceLocation
Loc = Node.getBeginLoc();
27 return SM.isMacroBodyExpansion(Loc) || SM.isMacroArgExpansion(Loc);
30 bool isNULLMacroExpansion(
const Stmt *Statement, ASTContext &Context) {
31 SourceManager &SM = Context.getSourceManager();
32 const LangOptions &LO = Context.getLangOpts();
33 SourceLocation Loc = Statement->getBeginLoc();
34 return SM.isMacroBodyExpansion(Loc) &&
35 Lexer::getImmediateMacroName(Loc, SM, LO) ==
"NULL";
39 return isNULLMacroExpansion(&Node, Finder->getASTContext());
42 StringRef getZeroLiteralToCompareWithForType(CastKind CastExprKind,
44 ASTContext &Context) {
45 switch (CastExprKind) {
46 case CK_IntegralToBoolean:
47 return Type->isUnsignedIntegerType() ?
"0u" :
"0";
49 case CK_FloatingToBoolean:
50 return Context.hasSameType(Type, Context.FloatTy) ?
"0.0f" :
"0.0";
52 case CK_PointerToBoolean:
53 case CK_MemberPointerToBoolean:
54 return Context.getLangOpts().CPlusPlus11 ?
"nullptr" :
"0";
57 llvm_unreachable(
"Unexpected cast kind");
61 bool isUnaryLogicalNotOperator(
const Stmt *Statement) {
62 const auto *UnaryOperatorExpr = dyn_cast<UnaryOperator>(Statement);
63 return UnaryOperatorExpr && UnaryOperatorExpr->getOpcode() == UO_LNot;
66 bool areParensNeededForOverloadedOperator(OverloadedOperatorKind OperatorKind) {
67 switch (OperatorKind) {
83 bool areParensNeededForStatement(
const Stmt *Statement) {
84 if (
const auto *OperatorCall = dyn_cast<CXXOperatorCallExpr>(Statement)) {
85 return areParensNeededForOverloadedOperator(OperatorCall->getOperator());
88 return isa<BinaryOperator>(Statement) || isa<UnaryOperator>(Statement);
91 void fixGenericExprCastToBool(DiagnosticBuilder &Diag,
92 const ImplicitCastExpr *Cast,
const Stmt *
Parent,
93 ASTContext &Context) {
96 bool InvertComparison =
97 Parent !=
nullptr && isUnaryLogicalNotOperator(Parent);
98 if (InvertComparison) {
99 SourceLocation ParentStartLoc = Parent->getBeginLoc();
100 SourceLocation ParentEndLoc =
101 cast<UnaryOperator>(
Parent)->getSubExpr()->getBeginLoc();
102 Diag << FixItHint::CreateRemoval(
103 CharSourceRange::getCharRange(ParentStartLoc, ParentEndLoc));
105 Parent = Context.getParents(*Parent)[0].get<Stmt>();
108 const Expr *SubExpr = Cast->getSubExpr();
110 bool NeedInnerParens = areParensNeededForStatement(SubExpr);
111 bool NeedOuterParens =
112 Parent !=
nullptr && areParensNeededForStatement(Parent);
114 std::string StartLocInsertion;
116 if (NeedOuterParens) {
117 StartLocInsertion +=
"(";
119 if (NeedInnerParens) {
120 StartLocInsertion +=
"(";
123 if (!StartLocInsertion.empty()) {
124 Diag << FixItHint::CreateInsertion(Cast->getBeginLoc(), StartLocInsertion);
127 std::string EndLocInsertion;
129 if (NeedInnerParens) {
130 EndLocInsertion +=
")";
133 if (InvertComparison) {
134 EndLocInsertion +=
" == ";
136 EndLocInsertion +=
" != ";
139 EndLocInsertion += getZeroLiteralToCompareWithForType(
140 Cast->getCastKind(), SubExpr->getType(), Context);
142 if (NeedOuterParens) {
143 EndLocInsertion +=
")";
146 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
147 Cast->getEndLoc(), 0, Context.getSourceManager(), Context.getLangOpts());
148 Diag << FixItHint::CreateInsertion(EndLoc, EndLocInsertion);
151 StringRef getEquivalentBoolLiteralForExpr(
const Expr *Expression,
152 ASTContext &Context) {
153 if (isNULLMacroExpansion(Expression, Context)) {
157 if (
const auto *IntLit = dyn_cast<IntegerLiteral>(Expression)) {
158 return (IntLit->getValue() == 0) ?
"false" :
"true";
161 if (
const auto *FloatLit = dyn_cast<FloatingLiteral>(Expression)) {
162 llvm::APFloat FloatLitAbsValue = FloatLit->getValue();
163 FloatLitAbsValue.clearSign();
164 return (FloatLitAbsValue.bitcastToAPInt() == 0) ?
"false" :
"true";
167 if (
const auto *CharLit = dyn_cast<CharacterLiteral>(Expression)) {
168 return (CharLit->getValue() == 0) ?
"false" :
"true";
171 if (isa<StringLiteral>(Expression->IgnoreCasts())) {
178 void fixGenericExprCastFromBool(DiagnosticBuilder &Diag,
179 const ImplicitCastExpr *Cast,
180 ASTContext &Context, StringRef OtherType) {
181 const Expr *SubExpr = Cast->getSubExpr();
182 bool NeedParens = !isa<ParenExpr>(SubExpr);
184 Diag << FixItHint::CreateInsertion(
186 (Twine(
"static_cast<") + OtherType +
">" + (NeedParens ?
"(" :
""))
190 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
191 Cast->getEndLoc(), 0, Context.getSourceManager(),
192 Context.getLangOpts());
194 Diag << FixItHint::CreateInsertion(EndLoc,
")");
198 StringRef getEquivalentForBoolLiteral(
const CXXBoolLiteralExpr *BoolLiteral,
199 QualType DestType, ASTContext &Context) {
201 if (!Context.getLangOpts().CPlusPlus11 &&
202 (DestType->isPointerType() || DestType->isMemberPointerType()) &&
203 BoolLiteral->getValue() ==
false) {
207 if (DestType->isFloatingType()) {
208 if (Context.hasSameType(DestType, Context.FloatTy)) {
209 return BoolLiteral->getValue() ?
"1.0f" :
"0.0f";
211 return BoolLiteral->getValue() ?
"1.0" :
"0.0";
214 if (DestType->isUnsignedIntegerType()) {
215 return BoolLiteral->getValue() ?
"1u" :
"0u";
217 return BoolLiteral->getValue() ?
"1" :
"0";
220 bool isCastAllowedInCondition(
const ImplicitCastExpr *Cast,
221 ASTContext &Context) {
222 std::queue<const Stmt *> Q;
225 for (
const auto &N : Context.getParents(*Q.front())) {
226 const Stmt *S = N.get<Stmt>();
229 if (isa<IfStmt>(S) || isa<ConditionalOperator>(S) || isa<ForStmt>(S) ||
230 isa<WhileStmt>(S) || isa<BinaryConditionalOperator>(S))
232 if (isa<ParenExpr>(S) || isa<ImplicitCastExpr>(S) ||
233 isUnaryLogicalNotOperator(S) ||
234 (isa<BinaryOperator>(S) && cast<BinaryOperator>(S)->isLogicalOp())) {
247 ImplicitBoolConversionCheck::ImplicitBoolConversionCheck(
250 AllowIntegerConditions(Options.get(
"AllowIntegerConditions", false)),
251 AllowPointerConditions(Options.get(
"AllowPointerConditions", false)) {}
255 Options.
store(Opts,
"AllowIntegerConditions", AllowIntegerConditions);
256 Options.
store(Opts,
"AllowPointerConditions", AllowPointerConditions);
266 auto exceptionCases =
267 expr(anyOf(allOf(isMacroExpansion(), unless(isNULLMacroExpansion())),
268 has(ignoringImplicit(memberExpr(hasDeclaration(fieldDecl(hasBitWidth(1)))))),
269 hasParent(explicitCastExpr())));
270 auto implicitCastFromBool = implicitCastExpr(
271 anyOf(hasCastKind(CK_IntegralCast), hasCastKind(CK_IntegralToFloating),
273 allOf(anyOf(hasCastKind(CK_NullToPointer),
274 hasCastKind(CK_NullToMemberPointer)),
275 hasSourceExpression(cxxBoolLiteral()))),
276 hasSourceExpression(expr(hasType(booleanType()))),
277 unless(exceptionCases));
279 binaryOperator(hasOperatorName(
"^"), hasLHS(implicitCastFromBool),
280 hasRHS(implicitCastFromBool));
283 anyOf(hasCastKind(CK_IntegralToBoolean),
284 hasCastKind(CK_FloatingToBoolean),
285 hasCastKind(CK_PointerToBoolean),
286 hasCastKind(CK_MemberPointerToBoolean)),
291 hasParent(stmt(anyOf(ifStmt(), whileStmt()), has(declStmt())))),
293 unless(exceptionCases), unless(has(boolXor)),
296 anyOf(hasParent(stmt().bind(
"parentStmt")), anything()),
297 unless(isInTemplateInstantiation()),
298 unless(hasAncestor(functionTemplateDecl())))
299 .bind(
"implicitCastToBool"),
302 auto boolComparison = binaryOperator(
303 anyOf(hasOperatorName(
"=="), hasOperatorName(
"!=")),
304 hasLHS(implicitCastFromBool), hasRHS(implicitCastFromBool));
305 auto boolOpAssignment =
306 binaryOperator(anyOf(hasOperatorName(
"|="), hasOperatorName(
"&=")),
307 hasLHS(expr(hasType(booleanType()))));
308 auto bitfieldAssignment = binaryOperator(
309 hasLHS(memberExpr(hasDeclaration(fieldDecl(hasBitWidth(1))))));
310 auto bitfieldConstruct = cxxConstructorDecl(hasDescendant(cxxCtorInitializer(
311 withInitializer(equalsBoundNode(
"implicitCastFromBool")),
312 forField(hasBitWidth(1)))));
315 implicitCastFromBool,
320 unless(hasParent(binaryOperator(anyOf(
321 boolComparison, boolXor, boolOpAssignment, bitfieldAssignment)))),
322 implicitCastExpr().bind(
"implicitCastFromBool"),
323 unless(hasParent(bitfieldConstruct)),
325 anyOf(hasParent(implicitCastExpr().bind(
"furtherImplicitCast")),
327 unless(isInTemplateInstantiation()),
328 unless(hasAncestor(functionTemplateDecl()))),
333 const MatchFinder::MatchResult &Result) {
334 if (
const auto *CastToBool =
335 Result.Nodes.getNodeAs<ImplicitCastExpr>(
"implicitCastToBool")) {
336 const auto *Parent = Result.Nodes.getNodeAs<Stmt>(
"parentStmt");
337 return handleCastToBool(CastToBool, Parent, *Result.Context);
340 if (
const auto *CastFromBool =
341 Result.Nodes.getNodeAs<ImplicitCastExpr>(
"implicitCastFromBool")) {
342 const auto *NextImplicitCast =
343 Result.Nodes.getNodeAs<ImplicitCastExpr>(
"furtherImplicitCast");
344 return handleCastFromBool(CastFromBool, NextImplicitCast, *Result.Context);
348 void ImplicitBoolConversionCheck::handleCastToBool(
const ImplicitCastExpr *Cast,
350 ASTContext &Context) {
351 if (AllowPointerConditions &&
352 (Cast->getCastKind() == CK_PointerToBoolean ||
353 Cast->getCastKind() == CK_MemberPointerToBoolean) &&
354 isCastAllowedInCondition(Cast, Context)) {
358 if (AllowIntegerConditions && Cast->getCastKind() == CK_IntegralToBoolean &&
359 isCastAllowedInCondition(Cast, Context)) {
363 auto Diag =
diag(Cast->getBeginLoc(),
"implicit conversion %0 -> bool")
364 << Cast->getSubExpr()->getType();
366 StringRef EquivalentLiteral =
367 getEquivalentBoolLiteralForExpr(Cast->getSubExpr(), Context);
368 if (!EquivalentLiteral.empty()) {
369 Diag << tooling::fixit::createReplacement(*Cast, EquivalentLiteral);
371 fixGenericExprCastToBool(Diag, Cast, Parent, Context);
375 void ImplicitBoolConversionCheck::handleCastFromBool(
376 const ImplicitCastExpr *Cast,
const ImplicitCastExpr *NextImplicitCast,
377 ASTContext &Context) {
379 NextImplicitCast ? NextImplicitCast->getType() : Cast->getType();
380 auto Diag =
diag(Cast->getBeginLoc(),
"implicit conversion bool -> %0")
383 if (
const auto *BoolLiteral =
384 dyn_cast<CXXBoolLiteralExpr>(Cast->getSubExpr())) {
385 Diag << tooling::fixit::createReplacement(
386 *Cast, getEquivalentForBoolLiteral(BoolLiteral, DestType, Context));
388 fixGenericExprCastFromBool(Diag, Cast, Context, DestType.getAsString());
SourceLocation Loc
'#' location in the include directive
AST_MATCHER(Expr, isMacroID)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
Base class for all clang-tidy checks.
const LangOptions & getLangOpts() const
Returns the language options from the context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
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.
static constexpr llvm::StringLiteral Name
std::map< std::string, std::string > OptionMap
===– 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.