11#include "clang/AST/Decl.h"
12#include "clang/AST/DeclBase.h"
13#include "clang/AST/Expr.h"
14#include "clang/AST/RecursiveASTVisitor.h"
15#include "clang/AST/Stmt.h"
16#include "clang/ASTMatchers/ASTMatchFinder.h"
17#include "clang/ASTMatchers/ASTMatchers.h"
18#include "clang/ASTMatchers/ASTMatchersInternal.h"
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/DiagnosticIDs.h"
21#include "clang/Basic/LLVM.h"
22#include "clang/Basic/SourceLocation.h"
23#include "llvm/ADT/BitmaskEnum.h"
24#include "llvm/Support/ErrorHandling.h"
37struct CognitiveComplexity final {
44 enum Criteria : uint8_t {
69 IncrementNesting = 1U << 1,
79 PenalizeNesting = 1U << 2,
81 All = Increment | PenalizeNesting | IncrementNesting,
83 LLVM_MARK_AS_BITMASK_ENUM(PenalizeNesting),
89 const SourceLocation Loc;
90 const unsigned short Nesting;
93 Detail(SourceLocation SLoc,
unsigned short CurrentNesting, Criteria Crit)
94 : Loc(SLoc), Nesting(CurrentNesting), C(Crit) {}
100 std::pair<unsigned, unsigned short> process()
const {
101 assert(C != Criteria::None &&
"invalid criteria");
104 unsigned short Increment = 0;
106 if (C == Criteria::All) {
107 Increment = 1 + Nesting;
109 }
else if (C == (Criteria::Increment | Criteria::IncrementNesting)) {
112 }
else if (C == Criteria::Increment) {
115 }
else if (C == Criteria::IncrementNesting) {
119 llvm_unreachable(
"should not get to here.");
122 return {MsgId, Increment};
127 static constexpr unsigned DefaultLimit = 25U;
133 static_assert(
sizeof(Detail) <= 8,
134 "Since we use SmallVector to minimize the amount of "
135 "allocations, we also need to consider the price we pay for "
136 "that in terms of stack usage. "
137 "Thus, it is good to minimize the size of the Detail struct.");
138 SmallVector<Detail, DefaultLimit> Details;
147 void account(SourceLocation Loc,
unsigned short Nesting, Criteria C);
156static constexpr std::array<StringRef, 4>
Msgs = {{
158 "+%0, including nesting penalty of %1, nesting level increased to %2",
161 "+%0, nesting level increased to %2",
167 "nesting level increased to %2",
170void CognitiveComplexity::account(SourceLocation Loc,
unsigned short Nesting,
173 assert(C != Criteria::None &&
"invalid criteria");
175 Details.emplace_back(Loc, Nesting, C);
176 const Detail &D = Details.back();
178 const auto [MsgId, Increase] = D.process();
185class FunctionASTVisitor final
186 :
public RecursiveASTVisitor<FunctionASTVisitor> {
187 using Base = RecursiveASTVisitor<FunctionASTVisitor>;
190 const bool IgnoreMacros;
193 unsigned short CurrentNestingLevel = 0;
198 using OBO = std::optional<BinaryOperator::Opcode>;
199 std::stack<OBO, SmallVector<OBO, 4>> BinaryOperatorsStack;
202 explicit FunctionASTVisitor(
const bool IgnoreMacros)
203 : IgnoreMacros(IgnoreMacros) {}
205 bool traverseStmtWithIncreasedNestingLevel(Stmt *Node) {
206 ++CurrentNestingLevel;
207 const bool ShouldContinue = Base::TraverseStmt(Node);
208 --CurrentNestingLevel;
209 return ShouldContinue;
212 bool traverseDeclWithIncreasedNestingLevel(Decl *Node) {
213 ++CurrentNestingLevel;
214 const bool ShouldContinue = Base::TraverseDecl(Node);
215 --CurrentNestingLevel;
216 return ShouldContinue;
219 bool TraverseIfStmt(IfStmt *Node,
bool InElseIf =
false) {
221 return Base::TraverseIfStmt(Node);
224 CognitiveComplexity::Criteria Reasons =
225 CognitiveComplexity::Criteria::None;
228 Reasons |= CognitiveComplexity::Criteria::Increment;
230 Reasons |= CognitiveComplexity::Criteria::IncrementNesting;
235 Reasons |= CognitiveComplexity::Criteria::PenalizeNesting;
238 CC.account(Node->getIfLoc(), CurrentNestingLevel, Reasons);
247 if (!TraverseStmt(Node->getInit()))
250 if (!TraverseStmt(Node->getCond()))
253 if (!traverseStmtWithIncreasedNestingLevel(Node->getInit()))
256 if (!traverseStmtWithIncreasedNestingLevel(Node->getCond()))
261 if (!traverseStmtWithIncreasedNestingLevel(Node->getThen()))
264 if (!Node->getElse())
267 if (
auto *E = dyn_cast<IfStmt>(Node->getElse()))
268 return TraverseIfStmt(E,
true);
271 CognitiveComplexity::Criteria Reasons =
272 CognitiveComplexity::Criteria::None;
275 Reasons |= CognitiveComplexity::Criteria::Increment;
277 Reasons |= CognitiveComplexity::Criteria::IncrementNesting;
281 CC.account(Node->getElseLoc(), CurrentNestingLevel, Reasons);
285 return traverseStmtWithIncreasedNestingLevel(Node->getElse());
289#define CurrentBinaryOperator BinaryOperatorsStack.top()
293 bool TraverseBinaryOperator(BinaryOperator *Op) {
294 if (!Op || !Op->isLogicalOp())
295 return Base::TraverseBinaryOperator(Op);
298 if (BinaryOperatorsStack.empty())
299 BinaryOperatorsStack.emplace();
304 CC.account(Op->getOperatorLoc(), CurrentNestingLevel,
305 CognitiveComplexity::Criteria::Increment);
309 const std::optional<BinaryOperator::Opcode> BinOpCopy(
314 const bool ShouldContinue = Base::TraverseBinaryOperator(Op);
319 return ShouldContinue;
324 bool TraverseCallExpr(CallExpr *Node) {
328 return Base::TraverseCallExpr(Node);
331 BinaryOperatorsStack.emplace();
332 const bool ShouldContinue = Base::TraverseCallExpr(Node);
334 BinaryOperatorsStack.pop();
336 return ShouldContinue;
339#undef CurrentBinaryOperator
341 bool TraverseStmt(Stmt *Node) {
343 return Base::TraverseStmt(Node);
345 if (IgnoreMacros && Node->getBeginLoc().isMacroID())
351 CognitiveComplexity::Criteria Reasons = CognitiveComplexity::Criteria::None;
352 SourceLocation Location = Node->getBeginLoc();
356 switch (Node->getStmtClass()) {
359 case Stmt::ConditionalOperatorClass:
360 case Stmt::SwitchStmtClass:
361 case Stmt::ForStmtClass:
362 case Stmt::CXXForRangeStmtClass:
363 case Stmt::WhileStmtClass:
364 case Stmt::DoStmtClass:
365 case Stmt::CXXCatchStmtClass:
366 case Stmt::GotoStmtClass:
367 case Stmt::IndirectGotoStmtClass:
368 Reasons |= CognitiveComplexity::Criteria::Increment;
379 switch (Node->getStmtClass()) {
382 case Stmt::ConditionalOperatorClass:
383 case Stmt::SwitchStmtClass:
384 case Stmt::ForStmtClass:
385 case Stmt::CXXForRangeStmtClass:
386 case Stmt::WhileStmtClass:
387 case Stmt::DoStmtClass:
388 case Stmt::CXXCatchStmtClass:
389 case Stmt::LambdaExprClass:
390 case Stmt::StmtExprClass:
391 Reasons |= CognitiveComplexity::Criteria::IncrementNesting;
400 switch (Node->getStmtClass()) {
402 case Stmt::ConditionalOperatorClass:
403 case Stmt::SwitchStmtClass:
404 case Stmt::ForStmtClass:
405 case Stmt::CXXForRangeStmtClass:
406 case Stmt::WhileStmtClass:
407 case Stmt::DoStmtClass:
408 case Stmt::CXXCatchStmtClass:
409 Reasons |= CognitiveComplexity::Criteria::PenalizeNesting;
415 if (Node->getStmtClass() == Stmt::ConditionalOperatorClass) {
419 Location = cast<ConditionalOperator>(Node)->getQuestionLoc();
423 if (Reasons & CognitiveComplexity::Criteria::All)
424 CC.account(Location, CurrentNestingLevel, Reasons);
427 if (!(Reasons & CognitiveComplexity::Criteria::IncrementNesting))
428 return Base::TraverseStmt(Node);
430 return traverseStmtWithIncreasedNestingLevel(Node);
442 bool TraverseDecl(Decl *Node,
bool MainAnalyzedFunction =
false) {
443 if (!Node || MainAnalyzedFunction)
444 return Base::TraverseDecl(Node);
448 switch (Node->getKind()) {
450 case Decl::CXXMethod:
451 case Decl::CXXConstructor:
452 case Decl::CXXDestructor:
457 return Base::TraverseDecl(Node);
461 CC.account(Node->getBeginLoc(), CurrentNestingLevel,
462 CognitiveComplexity::Criteria::IncrementNesting);
464 return traverseDeclWithIncreasedNestingLevel(Node);
467 CognitiveComplexity CC;
475 Threshold(Options.get(
"Threshold", CognitiveComplexity::DefaultLimit)),
476 DescribeBasicIncrements(Options.get(
"DescribeBasicIncrements", true)),
477 IgnoreMacros(Options.get(
"IgnoreMacros", false)) {}
481 Options.store(Opts,
"Threshold", Threshold);
482 Options.store(Opts,
"DescribeBasicIncrements", DescribeBasicIncrements);
483 Options.store(Opts,
"IgnoreMacros", IgnoreMacros);
488 functionDecl(isDefinition(),
489 unless(anyOf(isDefaulted(), isDeleted(), isWeak())))
492 Finder->addMatcher(lambdaExpr().bind(
"lambda"),
this);
496 const MatchFinder::MatchResult &Result) {
497 FunctionASTVisitor Visitor(IgnoreMacros);
500 const auto *TheDecl = Result.Nodes.getNodeAs<FunctionDecl>(
"func");
501 const auto *TheLambdaExpr = Result.Nodes.getNodeAs<LambdaExpr>(
"lambda");
503 assert(TheDecl->hasBody() &&
504 "The matchers should only match the functions that "
505 "have user-provided body.");
506 Loc = TheDecl->getLocation();
507 Visitor.TraverseDecl(
const_cast<FunctionDecl *
>(TheDecl),
true);
509 Loc = TheLambdaExpr->getBeginLoc();
510 Visitor.TraverseLambdaExpr(
const_cast<LambdaExpr *
>(TheLambdaExpr));
513 if (Visitor.CC.Total <= Threshold)
517 diag(Loc,
"function %0 has cognitive complexity of %1 (threshold %2)")
518 << TheDecl << Visitor.CC.Total << Threshold;
520 diag(Loc,
"lambda has cognitive complexity of %0 (threshold %1)")
521 << Visitor.CC.Total << Threshold;
523 if (!DescribeBasicIncrements)
527 for (
const auto &Detail : Visitor.CC.Details) {
528 auto [MsgId, Increase] = Detail.process();
529 assert(MsgId <
Msgs.size() &&
"MsgId should always be valid");
532 diag(Detail.Loc,
Msgs[MsgId], DiagnosticIDs::Note)
533 << Increase << Detail.Nesting << 1 + Detail.Nesting;
#define CurrentBinaryOperator
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
FunctionCognitiveComplexityCheck(StringRef Name, ClangTidyContext *Context)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
static constexpr std::array< StringRef, 4 > Msgs
llvm::StringMap< ClangTidyValue > OptionMap