11 #include "clang/AST/ASTContext.h" 12 #include "clang/AST/Expr.h" 13 #include "clang/ASTMatchers/ASTMatchFinder.h" 14 #include "clang/Frontend/CompilerInstance.h" 15 #include "clang/Lex/Lexer.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringRef.h" 18 #include "llvm/Support/Casting.h" 36 auto NegatedString = unaryOperator(
37 hasOperatorName(
"!"), hasUnaryOperand(ignoringImpCasts(stringLiteral())));
39 expr(anyOf(cxxBoolLiteral(equals(
false)), integerLiteral(equals(0)),
40 cxxNullPtrLiteralExpr(), gnuNullExpr(), NegatedString))
41 .bind(
"isAlwaysFalse");
42 auto IsAlwaysFalseWithCast = ignoringParenImpCasts(anyOf(
43 IsAlwaysFalse, cStyleCastExpr(has(ignoringParenImpCasts(IsAlwaysFalse)))
45 auto AssertExprRoot = anyOf(
47 anyOf(hasOperatorName(
"&&"), hasOperatorName(
"==")),
48 hasEitherOperand(ignoringImpCasts(stringLiteral().bind(
"assertMSG"))),
49 anyOf(binaryOperator(hasEitherOperand(IsAlwaysFalseWithCast)),
51 .bind(
"assertExprRoot"),
53 auto NonConstexprFunctionCall =
54 callExpr(hasDeclaration(functionDecl(unless(isConstexpr()))));
55 auto AssertCondition =
57 anyOf(expr(ignoringParenCasts(anyOf(
58 AssertExprRoot, unaryOperator(hasUnaryOperand(
59 ignoringParenCasts(AssertExprRoot)))))),
61 unless(findAll(NonConstexprFunctionCall)))
64 anyOf(ignoringParenImpCasts(callExpr(
65 hasDeclaration(functionDecl(hasName(
"__builtin_expect"))),
66 hasArgument(0, AssertCondition))),
69 Finder->addMatcher(conditionalOperator(hasCondition(Condition),
70 unless(isInTemplateInstantiation()))
75 ifStmt(hasCondition(Condition), unless(isInTemplateInstantiation()))
81 const ASTContext *ASTCtx = Result.Context;
82 const LangOptions &Opts = ASTCtx->getLangOpts();
83 const SourceManager &SM = ASTCtx->getSourceManager();
84 const auto *CondStmt = Result.Nodes.getNodeAs<Stmt>(
"condStmt");
85 const auto *Condition = Result.Nodes.getNodeAs<Expr>(
"condition");
86 const auto *IsAlwaysFalse = Result.Nodes.getNodeAs<Expr>(
"isAlwaysFalse");
87 const auto *AssertMSG = Result.Nodes.getNodeAs<StringLiteral>(
"assertMSG");
88 const auto *AssertExprRoot =
89 Result.Nodes.getNodeAs<BinaryOperator>(
"assertExprRoot");
90 const auto *CastExpr = Result.Nodes.getNodeAs<CStyleCastExpr>(
"castExpr");
91 SourceLocation AssertExpansionLoc = CondStmt->getLocStart();
93 if (!AssertExpansionLoc.isValid() || !AssertExpansionLoc.isMacroID())
97 Lexer::getImmediateMacroName(AssertExpansionLoc, SM, Opts);
99 if (MacroName !=
"assert" || Condition->isValueDependent() ||
100 Condition->isTypeDependent() || Condition->isInstantiationDependent() ||
101 !Condition->isEvaluatable(*ASTCtx))
105 if (IsAlwaysFalse && (!CastExpr || CastExpr->getType()->isPointerType())) {
106 SourceLocation FalseLiteralLoc =
107 SM.getImmediateSpellingLoc(IsAlwaysFalse->getExprLoc());
108 if (!FalseLiteralLoc.isMacroID())
111 StringRef FalseMacroName =
112 Lexer::getImmediateMacroName(FalseLiteralLoc, SM, Opts);
113 if (FalseMacroName.compare_lower(
"false") == 0 ||
114 FalseMacroName.compare_lower(
"null") == 0)
118 SourceLocation AssertLoc = SM.getImmediateMacroCallerLoc(AssertExpansionLoc);
120 SmallVector<FixItHint, 4> FixItHints;
121 SourceLocation LastParenLoc;
122 if (AssertLoc.isValid() && !AssertLoc.isMacroID() &&
123 (LastParenLoc = getLastParenLoc(ASTCtx, AssertLoc)).isValid()) {
124 FixItHints.push_back(
125 FixItHint::CreateReplacement(SourceRange(AssertLoc),
"static_assert"));
127 std::string StaticAssertMSG =
", \"\"";
128 if (AssertExprRoot) {
129 FixItHints.push_back(FixItHint::CreateRemoval(
130 SourceRange(AssertExprRoot->getOperatorLoc())));
131 FixItHints.push_back(FixItHint::CreateRemoval(
132 SourceRange(AssertMSG->getLocStart(), AssertMSG->getLocEnd())));
133 StaticAssertMSG = (Twine(
", \"") + AssertMSG->getString() +
"\"").str();
136 FixItHints.push_back(
137 FixItHint::CreateInsertion(LastParenLoc, StaticAssertMSG));
140 diag(AssertLoc,
"found assert() that could be replaced by static_assert()")
144 SourceLocation StaticAssertCheck::getLastParenLoc(
const ASTContext *ASTCtx,
145 SourceLocation AssertLoc) {
146 const LangOptions &Opts = ASTCtx->getLangOpts();
147 const SourceManager &SM = ASTCtx->getSourceManager();
149 llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getFileID(AssertLoc));
151 return SourceLocation();
153 const char *BufferPos = SM.getCharacterData(AssertLoc);
156 Lexer Lexer(SM.getLocForStartOfFile(SM.getFileID(AssertLoc)), Opts,
157 Buffer->getBufferStart(), BufferPos, Buffer->getBufferEnd());
160 if (Lexer.LexFromRawLexer(Token) || Lexer.LexFromRawLexer(Token) ||
161 !Token.is(tok::l_paren))
162 return SourceLocation();
164 unsigned int ParenCount = 1;
165 while (ParenCount && !Lexer.LexFromRawLexer(Token)) {
166 if (Token.is(tok::l_paren))
168 else if (Token.is(tok::r_paren))
172 return Token.getLocation();
LangOptions getLangOpts() const
Returns the language options from the context.
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.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.