1//===--- StaticAssertCheck.cpp - clang-tidy -------------------------------===//
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
9#include "StaticAssertCheck.h"
10#include "../utils/Matchers.h"
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/StringRef.h"
17#include <optional>
18#include <string>
19
20using namespace clang::ast_matchers;
21
22namespace clang::tidy::misc {
23
24StaticAssertCheck::StaticAssertCheck(StringRef Name, ClangTidyContext *Context)
25 : ClangTidyCheck(Name, Context) {}
26
27void StaticAssertCheck::registerMatchers(MatchFinder *Finder) {
28 auto NegatedString = unaryOperator(
29 hasOperatorName(Name: "!"), hasUnaryOperand(InnerMatcher: ignoringImpCasts(InnerMatcher: stringLiteral())));
30 auto IsAlwaysFalse =
31 expr(anyOf(cxxBoolLiteral(equals(Value: false)), integerLiteral(equals(Value: 0)),
32 cxxNullPtrLiteralExpr(), gnuNullExpr(), NegatedString))
33 .bind(ID: "isAlwaysFalse");
34 auto IsAlwaysFalseWithCast = ignoringParenImpCasts(InnerMatcher: anyOf(
35 IsAlwaysFalse, cStyleCastExpr(has(ignoringParenImpCasts(InnerMatcher: IsAlwaysFalse)))
36 .bind(ID: "castExpr")));
37 auto AssertExprRoot = anyOf(
38 binaryOperator(
39 hasAnyOperatorName("&&", "=="),
40 hasEitherOperand(InnerMatcher: ignoringImpCasts(InnerMatcher: stringLiteral().bind(ID: "assertMSG"))),
41 optionally(binaryOperator(hasEitherOperand(InnerMatcher: IsAlwaysFalseWithCast))))
42 .bind(ID: "assertExprRoot"),
43 IsAlwaysFalse);
44 auto NonConstexprFunctionCall =
45 callExpr(hasDeclaration(InnerMatcher: functionDecl(unless(isConstexpr()))));
46 auto NonConstexprVariableReference =
47 declRefExpr(to(InnerMatcher: varDecl(unless(isConstexpr()))),
48 unless(hasAncestor(expr(matchers::hasUnevaluatedContext()))),
49 unless(hasAncestor(typeLoc())));
50
51 auto NonConstexprCode =
52 expr(anyOf(NonConstexprFunctionCall, NonConstexprVariableReference));
53 auto AssertCondition =
54 expr(optionally(expr(ignoringParenCasts(InnerMatcher: anyOf(
55 AssertExprRoot, unaryOperator(hasUnaryOperand(
56 InnerMatcher: ignoringParenCasts(InnerMatcher: AssertExprRoot))))))),
57 unless(NonConstexprCode), unless(hasDescendant(NonConstexprCode)))
58 .bind(ID: "condition");
59 auto Condition =
60 anyOf(ignoringParenImpCasts(InnerMatcher: callExpr(
61 hasDeclaration(InnerMatcher: functionDecl(hasName(Name: "__builtin_expect"))),
62 hasArgument(N: 0, InnerMatcher: AssertCondition))),
63 AssertCondition);
64
65 Finder->addMatcher(NodeMatch: conditionalOperator(hasCondition(InnerMatcher: Condition),
66 unless(isInTemplateInstantiation()))
67 .bind(ID: "condStmt"),
68 Action: this);
69
70 Finder->addMatcher(
71 NodeMatch: ifStmt(hasCondition(InnerMatcher: Condition), unless(isInTemplateInstantiation()))
72 .bind(ID: "condStmt"),
73 Action: this);
74}
75
76void StaticAssertCheck::check(const MatchFinder::MatchResult &Result) {
77 const ASTContext *ASTCtx = Result.Context;
78 const LangOptions &Opts = ASTCtx->getLangOpts();
79 const SourceManager &SM = ASTCtx->getSourceManager();
80 const auto *CondStmt = Result.Nodes.getNodeAs<Stmt>(ID: "condStmt");
81 const auto *Condition = Result.Nodes.getNodeAs<Expr>(ID: "condition");
82 const auto *IsAlwaysFalse = Result.Nodes.getNodeAs<Expr>(ID: "isAlwaysFalse");
83 const auto *AssertMSG = Result.Nodes.getNodeAs<StringLiteral>(ID: "assertMSG");
84 const auto *AssertExprRoot =
85 Result.Nodes.getNodeAs<BinaryOperator>(ID: "assertExprRoot");
86 const auto *CastExpr = Result.Nodes.getNodeAs<CStyleCastExpr>(ID: "castExpr");
87 SourceLocation AssertExpansionLoc = CondStmt->getBeginLoc();
88
89 if (!AssertExpansionLoc.isValid() || !AssertExpansionLoc.isMacroID())
90 return;
91
92 StringRef MacroName =
93 Lexer::getImmediateMacroName(Loc: AssertExpansionLoc, SM, LangOpts: Opts);
94
95 if (MacroName != "assert" || Condition->isValueDependent() ||
96 Condition->isTypeDependent() || Condition->isInstantiationDependent() ||
97 !Condition->isEvaluatable(Ctx: *ASTCtx))
98 return;
99
100 // False literal is not the result of macro expansion.
101 if (IsAlwaysFalse && (!CastExpr || CastExpr->getType()->isPointerType())) {
102 SourceLocation FalseLiteralLoc =
103 SM.getImmediateSpellingLoc(Loc: IsAlwaysFalse->getExprLoc());
104 if (!FalseLiteralLoc.isMacroID())
105 return;
106
107 StringRef FalseMacroName =
108 Lexer::getImmediateMacroName(Loc: FalseLiteralLoc, SM, LangOpts: Opts);
109 if (FalseMacroName.compare_insensitive(RHS: "false") == 0 ||
110 FalseMacroName.compare_insensitive(RHS: "null") == 0)
111 return;
112 }
113
114 SourceLocation AssertLoc = SM.getImmediateMacroCallerLoc(Loc: AssertExpansionLoc);
115
116 SmallVector<FixItHint, 4> FixItHints;
117 SourceLocation LastParenLoc;
118 if (AssertLoc.isValid() && !AssertLoc.isMacroID() &&
119 (LastParenLoc = getLastParenLoc(ASTCtx, AssertLoc)).isValid()) {
120 FixItHints.push_back(
121 Elt: FixItHint::CreateReplacement(RemoveRange: SourceRange(AssertLoc), Code: "static_assert"));
122
123 if (AssertExprRoot) {
124 FixItHints.push_back(Elt: FixItHint::CreateRemoval(
125 RemoveRange: SourceRange(AssertExprRoot->getOperatorLoc())));
126 FixItHints.push_back(Elt: FixItHint::CreateRemoval(
127 RemoveRange: SourceRange(AssertMSG->getBeginLoc(), AssertMSG->getEndLoc())));
128 FixItHints.push_back(Elt: FixItHint::CreateInsertion(
129 InsertionLoc: LastParenLoc, Code: (Twine(", \"") + AssertMSG->getString() + "\"").str()));
130 } else if (!Opts.CPlusPlus17) {
131 FixItHints.push_back(Elt: FixItHint::CreateInsertion(InsertionLoc: LastParenLoc, Code: ", \"\""));
132 }
133 }
134
135 diag(Loc: AssertLoc, Description: "found assert() that could be replaced by static_assert()")
136 << FixItHints;
137}
138
139SourceLocation StaticAssertCheck::getLastParenLoc(const ASTContext *ASTCtx,
140 SourceLocation AssertLoc) {
141 const LangOptions &Opts = ASTCtx->getLangOpts();
142 const SourceManager &SM = ASTCtx->getSourceManager();
143
144 std::optional<llvm::MemoryBufferRef> Buffer =
145 SM.getBufferOrNone(FID: SM.getFileID(SpellingLoc: AssertLoc));
146 if (!Buffer)
147 return {};
148
149 const char *BufferPos = SM.getCharacterData(SL: AssertLoc);
150
151 Token Token;
152 Lexer Lexer(SM.getLocForStartOfFile(FID: SM.getFileID(SpellingLoc: AssertLoc)), Opts,
153 Buffer->getBufferStart(), BufferPos, Buffer->getBufferEnd());
154
155 // assert first left parenthesis
156 if (Lexer.LexFromRawLexer(Result&: Token) || Lexer.LexFromRawLexer(Result&: Token) ||
157 !Token.is(K: tok::l_paren))
158 return {};
159
160 unsigned int ParenCount = 1;
161 while (ParenCount && !Lexer.LexFromRawLexer(Result&: Token)) {
162 if (Token.is(K: tok::l_paren))
163 ++ParenCount;
164 else if (Token.is(K: tok::r_paren))
165 --ParenCount;
166 }
167
168 return Token.getLocation();
169}
170
171} // namespace clang::tidy::misc
172

source code of clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp