clang-tools  3.9.0
StaticAssertCheck.cpp
Go to the documentation of this file.
1 //===--- StaticAssertCheck.cpp - clang-tidy -------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "StaticAssertCheck.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/SmallVector.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Support/Casting.h"
19 #include <string>
20 
21 using namespace clang::ast_matchers;
22 
23 namespace clang {
24 namespace tidy {
25 namespace misc {
26 
27 StaticAssertCheck::StaticAssertCheck(StringRef Name, ClangTidyContext *Context)
28  : ClangTidyCheck(Name, Context) {}
29 
31  // This checker only makes sense for languages that have static assertion
32  // capabilities: C++11 and C11.
33  if (!(getLangOpts().CPlusPlus11 || getLangOpts().C11))
34  return;
35 
36  auto IsAlwaysFalse =
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)))
42  .bind("castExpr")));
43  auto AssertExprRoot = anyOf(
44  binaryOperator(
45  anyOf(hasOperatorName("&&"), hasOperatorName("==")),
46  hasEitherOperand(ignoringImpCasts(stringLiteral().bind("assertMSG"))),
47  anyOf(binaryOperator(hasEitherOperand(IsAlwaysFalseWithCast)),
48  anything()))
49  .bind("assertExprRoot"),
50  IsAlwaysFalse);
51  auto NonConstexprFunctionCall =
52  callExpr(hasDeclaration(functionDecl(unless(isConstexpr()))));
53  auto AssertCondition =
54  expr(
55  anyOf(expr(ignoringParenCasts(anyOf(
56  AssertExprRoot, unaryOperator(hasUnaryOperand(
57  ignoringParenCasts(AssertExprRoot)))))),
58  anything()),
59  unless(findAll(NonConstexprFunctionCall)))
60  .bind("condition");
61  auto Condition =
62  anyOf(ignoringParenImpCasts(callExpr(
63  hasDeclaration(functionDecl(hasName("__builtin_expect"))),
64  hasArgument(0, AssertCondition))),
65  AssertCondition);
66 
67  Finder->addMatcher(conditionalOperator(hasCondition(Condition),
68  unless(isInTemplateInstantiation()))
69  .bind("condStmt"),
70  this);
71 
72  Finder->addMatcher(
73  ifStmt(hasCondition(Condition), unless(isInTemplateInstantiation()))
74  .bind("condStmt"),
75  this);
76 }
77 
78 void StaticAssertCheck::check(const MatchFinder::MatchResult &Result) {
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();
90 
91  if (!AssertExpansionLoc.isValid() || !AssertExpansionLoc.isMacroID())
92  return;
93 
94  StringRef MacroName =
95  Lexer::getImmediateMacroName(AssertExpansionLoc, SM, Opts);
96 
97  if (MacroName != "assert" || Condition->isValueDependent() ||
98  Condition->isTypeDependent() || Condition->isInstantiationDependent() ||
99  !Condition->isEvaluatable(*ASTCtx))
100  return;
101 
102  // False literal is not the result of macro expansion.
103  if (IsAlwaysFalse && (!CastExpr || CastExpr->getType()->isPointerType())) {
104  SourceLocation FalseLiteralLoc =
105  SM.getImmediateSpellingLoc(IsAlwaysFalse->getExprLoc());
106  if (!FalseLiteralLoc.isMacroID())
107  return;
108 
109  StringRef FalseMacroName =
110  Lexer::getImmediateMacroName(FalseLiteralLoc, SM, Opts);
111  if (FalseMacroName.compare_lower("false") == 0 ||
112  FalseMacroName.compare_lower("null") == 0)
113  return;
114  }
115 
116  SourceLocation AssertLoc = SM.getImmediateMacroCallerLoc(AssertExpansionLoc);
117 
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"));
124 
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();
132  }
133 
134  FixItHints.push_back(
135  FixItHint::CreateInsertion(LastParenLoc, StaticAssertMSG));
136  }
137 
138  diag(AssertLoc, "found assert() that could be replaced by static_assert()")
139  << FixItHints;
140 }
141 
142 SourceLocation StaticAssertCheck::getLastParenLoc(const ASTContext *ASTCtx,
143  SourceLocation AssertLoc) {
144  const LangOptions &Opts = ASTCtx->getLangOpts();
145  const SourceManager &SM = ASTCtx->getSourceManager();
146 
147  llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getFileID(AssertLoc));
148  if (!Buffer)
149  return SourceLocation();
150 
151  const char *BufferPos = SM.getCharacterData(AssertLoc);
152 
153  Token Token;
154  Lexer Lexer(SM.getLocForStartOfFile(SM.getFileID(AssertLoc)), Opts,
155  Buffer->getBufferStart(), BufferPos, Buffer->getBufferEnd());
156 
157  // assert first left parenthesis
158  if (Lexer.LexFromRawLexer(Token) || Lexer.LexFromRawLexer(Token) ||
159  !Token.is(tok::l_paren))
160  return SourceLocation();
161 
162  unsigned int ParenCount = 1;
163  while (ParenCount && !Lexer.LexFromRawLexer(Token)) {
164  if (Token.is(tok::l_paren))
165  ++ParenCount;
166  else if (Token.is(tok::r_paren))
167  --ParenCount;
168  }
169 
170  return Token.getLocation();
171 }
172 
173 } // namespace misc
174 } // namespace tidy
175 } // namespace clang
const std::string Name
Definition: USRFinder.cpp:140
LangOptions getLangOpts() const
Returns the language options from the context.
Definition: ClangTidy.h:170
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:210
Base class for all clang-tidy checks.
Definition: ClangTidy.h:110
SourceManager & SM
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
Definition: ClangTidy.cpp:93
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.
Definition: ClangTidy.cpp:352
const NamedDecl * Result
Definition: USRFinder.cpp:137