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"
36struct CognitiveComplexity final {
43 enum Criteria : uint8_t {
68 IncrementNesting = 1U << 1,
78 PenalizeNesting = 1U << 2,
80 All = Increment | PenalizeNesting | IncrementNesting,
82 LLVM_MARK_AS_BITMASK_ENUM(PenalizeNesting),
88 const SourceLocation Loc;
89 const unsigned short Nesting;
92 Detail(SourceLocation SLoc,
unsigned short CurrentNesting, Criteria Crit)
93 : Loc(SLoc), Nesting(CurrentNesting), C(Crit) {}
99 std::pair<unsigned, unsigned short> process()
const {
100 assert(C != Criteria::None &&
"invalid criteria");
103 unsigned short Increment = 0;
105 if (C == Criteria::All) {
106 Increment = 1 + Nesting;
108 }
else if (C == (Criteria::Increment | Criteria::IncrementNesting)) {
111 }
else if (C == Criteria::Increment) {
114 }
else if (C == Criteria::IncrementNesting) {
118 llvm_unreachable(
"should not get to here.");
121 return {MsgId, Increment};
126 static constexpr unsigned DefaultLimit = 25U;
132 static_assert(
sizeof(Detail) <= 8,
133 "Since we use SmallVector to minimize the amount of "
134 "allocations, we also need to consider the price we pay for "
135 "that in terms of stack usage. "
136 "Thus, it is good to minimize the size of the Detail struct.");
137 SmallVector<Detail, DefaultLimit> Details;
146 void account(SourceLocation Loc,
unsigned short Nesting, Criteria C);
155static constexpr std::array<StringRef, 4>
Msgs = {{
157 "+%0, including nesting penalty of %1, nesting level increased to %2",
160 "+%0, nesting level increased to %2",
166 "nesting level increased to %2",
169void CognitiveComplexity::account(SourceLocation Loc,
unsigned short Nesting,
172 assert(C != Criteria::None &&
"invalid criteria");
174 Details.emplace_back(Loc, Nesting, C);
175 const Detail &D = Details.back();
177 const auto [MsgId, Increase] = D.process();
184class FunctionASTVisitor final
185 :
public RecursiveASTVisitor<FunctionASTVisitor> {
186 using Base = RecursiveASTVisitor<FunctionASTVisitor>;
189 const bool IgnoreMacros;
192 unsigned short CurrentNestingLevel = 0;
197 using OBO = std::optional<BinaryOperator::Opcode>;
198 std::stack<OBO, SmallVector<OBO, 4>> BinaryOperatorsStack;
201 explicit FunctionASTVisitor(
const bool IgnoreMacros)
202 : IgnoreMacros(IgnoreMacros) {}
204 bool traverseStmtWithIncreasedNestingLevel(Stmt *Node) {
205 ++CurrentNestingLevel;
206 const bool ShouldContinue = Base::TraverseStmt(Node);
207 --CurrentNestingLevel;
208 return ShouldContinue;
211 bool traverseDeclWithIncreasedNestingLevel(Decl *Node) {
212 ++CurrentNestingLevel;
213 const bool ShouldContinue = Base::TraverseDecl(Node);
214 --CurrentNestingLevel;
215 return ShouldContinue;
218 bool TraverseIfStmt(IfStmt *Node,
bool InElseIf =
false) {
220 return Base::TraverseIfStmt(Node);
223 CognitiveComplexity::Criteria Reasons =
224 CognitiveComplexity::Criteria::None;
227 Reasons |= CognitiveComplexity::Criteria::Increment;
229 Reasons |= CognitiveComplexity::Criteria::IncrementNesting;
234 Reasons |= CognitiveComplexity::Criteria::PenalizeNesting;
237 CC.account(Node->getIfLoc(), CurrentNestingLevel, Reasons);
246 if (!TraverseStmt(Node->getInit()))
249 if (!TraverseStmt(Node->getCond()))
252 if (!traverseStmtWithIncreasedNestingLevel(Node->getInit()))
255 if (!traverseStmtWithIncreasedNestingLevel(Node->getCond()))
260 if (!traverseStmtWithIncreasedNestingLevel(Node->getThen()))
263 if (!Node->getElse())
266 if (
auto *E = dyn_cast<IfStmt>(Node->getElse()))
267 return TraverseIfStmt(E,
true);
270 CognitiveComplexity::Criteria Reasons =
271 CognitiveComplexity::Criteria::None;
274 Reasons |= CognitiveComplexity::Criteria::Increment;
276 Reasons |= CognitiveComplexity::Criteria::IncrementNesting;
280 CC.account(Node->getElseLoc(), CurrentNestingLevel, Reasons);
284 return traverseStmtWithIncreasedNestingLevel(Node->getElse());
288#define CurrentBinaryOperator BinaryOperatorsStack.top()
292 bool TraverseBinaryOperator(BinaryOperator *Op) {
293 if (!Op || !Op->isLogicalOp())
294 return Base::TraverseBinaryOperator(Op);
297 if (BinaryOperatorsStack.empty())
298 BinaryOperatorsStack.emplace();
303 CC.account(Op->getOperatorLoc(), CurrentNestingLevel,
304 CognitiveComplexity::Criteria::Increment);
308 const std::optional<BinaryOperator::Opcode> BinOpCopy(
313 const bool ShouldContinue = Base::TraverseBinaryOperator(Op);
318 return ShouldContinue;
323 bool TraverseCallExpr(CallExpr *Node) {
327 return Base::TraverseCallExpr(Node);
330 BinaryOperatorsStack.emplace();
331 const bool ShouldContinue = Base::TraverseCallExpr(Node);
333 BinaryOperatorsStack.pop();
335 return ShouldContinue;
338#undef CurrentBinaryOperator
340 bool TraverseStmt(Stmt *Node) {
342 return Base::TraverseStmt(Node);
344 if (IgnoreMacros && Node->getBeginLoc().isMacroID())
350 CognitiveComplexity::Criteria Reasons = CognitiveComplexity::Criteria::None;
351 SourceLocation Location = Node->getBeginLoc();
355 switch (Node->getStmtClass()) {
358 case Stmt::ConditionalOperatorClass:
359 case Stmt::SwitchStmtClass:
360 case Stmt::ForStmtClass:
361 case Stmt::CXXForRangeStmtClass:
362 case Stmt::WhileStmtClass:
363 case Stmt::DoStmtClass:
364 case Stmt::CXXCatchStmtClass:
365 case Stmt::GotoStmtClass:
366 case Stmt::IndirectGotoStmtClass:
367 Reasons |= CognitiveComplexity::Criteria::Increment;
378 switch (Node->getStmtClass()) {
381 case Stmt::ConditionalOperatorClass:
382 case Stmt::SwitchStmtClass:
383 case Stmt::ForStmtClass:
384 case Stmt::CXXForRangeStmtClass:
385 case Stmt::WhileStmtClass:
386 case Stmt::DoStmtClass:
387 case Stmt::CXXCatchStmtClass:
388 case Stmt::LambdaExprClass:
389 case Stmt::StmtExprClass:
390 Reasons |= CognitiveComplexity::Criteria::IncrementNesting;
399 switch (Node->getStmtClass()) {
401 case Stmt::ConditionalOperatorClass:
402 case Stmt::SwitchStmtClass:
403 case Stmt::ForStmtClass:
404 case Stmt::CXXForRangeStmtClass:
405 case Stmt::WhileStmtClass:
406 case Stmt::DoStmtClass:
407 case Stmt::CXXCatchStmtClass:
408 Reasons |= CognitiveComplexity::Criteria::PenalizeNesting;
414 if (Node->getStmtClass() == Stmt::ConditionalOperatorClass) {
418 Location = cast<ConditionalOperator>(Node)->getQuestionLoc();
422 if (Reasons & CognitiveComplexity::Criteria::All)
423 CC.account(Location, CurrentNestingLevel, Reasons);
426 if (!(Reasons & CognitiveComplexity::Criteria::IncrementNesting))
427 return Base::TraverseStmt(Node);
429 return traverseStmtWithIncreasedNestingLevel(Node);
441 bool TraverseDecl(Decl *Node,
bool MainAnalyzedFunction =
false) {
442 if (!Node || MainAnalyzedFunction)
443 return Base::TraverseDecl(Node);
447 switch (Node->getKind()) {
449 case Decl::CXXMethod:
450 case Decl::CXXConstructor:
451 case Decl::CXXDestructor:
456 return Base::TraverseDecl(Node);
460 CC.account(Node->getBeginLoc(), CurrentNestingLevel,
461 CognitiveComplexity::Criteria::IncrementNesting);
463 return traverseDeclWithIncreasedNestingLevel(Node);
466 CognitiveComplexity CC;
474 Threshold(Options.get(
"Threshold", CognitiveComplexity::DefaultLimit)),
475 DescribeBasicIncrements(Options.get(
"DescribeBasicIncrements", true)),
476 IgnoreMacros(Options.get(
"IgnoreMacros", false)) {}
480 Options.store(Opts,
"Threshold", Threshold);
481 Options.store(Opts,
"DescribeBasicIncrements", DescribeBasicIncrements);
482 Options.store(Opts,
"IgnoreMacros", IgnoreMacros);
487 functionDecl(isDefinition(),
488 unless(anyOf(isDefaulted(), isDeleted(), isWeak())))
491 Finder->addMatcher(lambdaExpr().bind(
"lambda"),
this);
495 const MatchFinder::MatchResult &Result) {
496 FunctionASTVisitor Visitor(IgnoreMacros);
499 const auto *TheDecl = Result.Nodes.getNodeAs<FunctionDecl>(
"func");
500 const auto *TheLambdaExpr = Result.Nodes.getNodeAs<LambdaExpr>(
"lambda");
502 assert(TheDecl->hasBody() &&
503 "The matchers should only match the functions that "
504 "have user-provided body.");
505 Loc = TheDecl->getLocation();
506 Visitor.TraverseDecl(
const_cast<FunctionDecl *
>(TheDecl),
true);
508 Loc = TheLambdaExpr->getBeginLoc();
509 Visitor.TraverseLambdaExpr(
const_cast<LambdaExpr *
>(TheLambdaExpr));
512 if (Visitor.CC.Total <= Threshold)
516 diag(Loc,
"function %0 has cognitive complexity of %1 (threshold %2)")
517 << TheDecl << Visitor.CC.Total << Threshold;
519 diag(Loc,
"lambda has cognitive complexity of %0 (threshold %1)")
520 << Visitor.CC.Total << Threshold;
522 if (!DescribeBasicIncrements)
526 for (
const auto &Detail : Visitor.CC.Details) {
527 auto [MsgId, Increase] = Detail.process();
528 assert(MsgId <
Msgs.size() &&
"MsgId should always be valid");
531 diag(Detail.Loc,
Msgs[MsgId], DiagnosticIDs::Note)
532 << 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