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"
21 using namespace clang::ast_matchers;
37 expr(anyOf(cxxBoolLiteral(equals(
false)), integerLiteral(equals(0)),
38 cxxNullPtrLiteralExpr(), gnuNullExpr()))
39 .bind(
"isAlwaysFalse");
40 auto IsAlwaysFalseWithCast = ignoringParenImpCasts(anyOf(
41 IsAlwaysFalse, cStyleCastExpr(has(ignoringParenImpCasts(IsAlwaysFalse)))
43 auto AssertExprRoot = anyOf(
45 anyOf(hasOperatorName(
"&&"), hasOperatorName(
"==")),
46 hasEitherOperand(ignoringImpCasts(stringLiteral().bind(
"assertMSG"))),
47 anyOf(binaryOperator(hasEitherOperand(IsAlwaysFalseWithCast)),
49 .bind(
"assertExprRoot"),
51 auto NonConstexprFunctionCall =
52 callExpr(hasDeclaration(functionDecl(unless(isConstexpr()))));
53 auto AssertCondition =
55 anyOf(expr(ignoringParenCasts(anyOf(
56 AssertExprRoot, unaryOperator(hasUnaryOperand(
57 ignoringParenCasts(AssertExprRoot)))))),
59 unless(findAll(NonConstexprFunctionCall)))
62 anyOf(ignoringParenImpCasts(callExpr(
63 hasDeclaration(functionDecl(hasName(
"__builtin_expect"))),
64 hasArgument(0, AssertCondition))),
67 Finder->addMatcher(conditionalOperator(hasCondition(Condition),
68 unless(isInTemplateInstantiation()))
73 ifStmt(hasCondition(Condition), unless(isInTemplateInstantiation()))
79 const ASTContext *ASTCtx = Result.Context;
80 const LangOptions &Opts = ASTCtx->getLangOpts();
81 const SourceManager &
SM = ASTCtx->getSourceManager();
82 const auto *CondStmt = Result.Nodes.getNodeAs<Stmt>(
"condStmt");
83 const auto *Condition = Result.Nodes.getNodeAs<Expr>(
"condition");
84 const auto *IsAlwaysFalse = Result.Nodes.getNodeAs<Expr>(
"isAlwaysFalse");
85 const auto *AssertMSG = Result.Nodes.getNodeAs<StringLiteral>(
"assertMSG");
86 const auto *AssertExprRoot =
87 Result.Nodes.getNodeAs<BinaryOperator>(
"assertExprRoot");
88 const auto *CastExpr = Result.Nodes.getNodeAs<CStyleCastExpr>(
"castExpr");
89 SourceLocation AssertExpansionLoc = CondStmt->getLocStart();
91 if (!AssertExpansionLoc.isValid() || !AssertExpansionLoc.isMacroID())
95 Lexer::getImmediateMacroName(AssertExpansionLoc, SM, Opts);
97 if (MacroName !=
"assert" || Condition->isValueDependent() ||
98 Condition->isTypeDependent() || Condition->isInstantiationDependent() ||
99 !Condition->isEvaluatable(*ASTCtx))
103 if (IsAlwaysFalse && (!CastExpr || CastExpr->getType()->isPointerType())) {
104 SourceLocation FalseLiteralLoc =
105 SM.getImmediateSpellingLoc(IsAlwaysFalse->getExprLoc());
106 if (!FalseLiteralLoc.isMacroID())
109 StringRef FalseMacroName =
110 Lexer::getImmediateMacroName(FalseLiteralLoc, SM, Opts);
111 if (FalseMacroName.compare_lower(
"false") == 0 ||
112 FalseMacroName.compare_lower(
"null") == 0)
116 SourceLocation AssertLoc = SM.getImmediateMacroCallerLoc(AssertExpansionLoc);
118 SmallVector<FixItHint, 4> FixItHints;
119 SourceLocation LastParenLoc;
120 if (AssertLoc.isValid() && !AssertLoc.isMacroID() &&
121 (LastParenLoc = getLastParenLoc(ASTCtx, AssertLoc)).isValid()) {
122 FixItHints.push_back(
123 FixItHint::CreateReplacement(SourceRange(AssertLoc),
"static_assert"));
125 std::string StaticAssertMSG =
", \"\"";
126 if (AssertExprRoot) {
127 FixItHints.push_back(FixItHint::CreateRemoval(
128 SourceRange(AssertExprRoot->getOperatorLoc())));
129 FixItHints.push_back(FixItHint::CreateRemoval(
130 SourceRange(AssertMSG->getLocStart(), AssertMSG->getLocEnd())));
131 StaticAssertMSG = (Twine(
", \"") + AssertMSG->getString() +
"\"").str();
134 FixItHints.push_back(
135 FixItHint::CreateInsertion(LastParenLoc, StaticAssertMSG));
138 diag(AssertLoc,
"found assert() that could be replaced by static_assert()")
142 SourceLocation StaticAssertCheck::getLastParenLoc(
const ASTContext *ASTCtx,
143 SourceLocation AssertLoc) {
144 const LangOptions &Opts = ASTCtx->getLangOpts();
145 const SourceManager &
SM = ASTCtx->getSourceManager();
147 llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getFileID(AssertLoc));
149 return SourceLocation();
151 const char *BufferPos = SM.getCharacterData(AssertLoc);
154 Lexer Lexer(SM.getLocForStartOfFile(SM.getFileID(AssertLoc)), Opts,
155 Buffer->getBufferStart(), BufferPos, Buffer->getBufferEnd());
158 if (Lexer.LexFromRawLexer(Token) || Lexer.LexFromRawLexer(Token) ||
159 !Token.is(tok::l_paren))
160 return SourceLocation();
162 unsigned int ParenCount = 1;
163 while (ParenCount && !Lexer.LexFromRawLexer(Token)) {
164 if (Token.is(tok::l_paren))
166 else if (Token.is(tok::r_paren))
170 return Token.getLocation();
LangOptions getLangOpts() const
Returns the language options from the context.
std::unique_ptr< ast_matchers::MatchFinder > 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.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
ClangTidyContext & Context
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.