clang-tools 24.0.0git
FunctionCognitiveComplexityCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
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"
25#include <array>
26#include <cassert>
27#include <optional>
28#include <stack>
29#include <tuple>
30#include <utility>
31
32using namespace clang::ast_matchers;
33
35namespace {
36
37struct CognitiveComplexity final {
38 // Any increment is based on some combination of reasons.
39 // For details you can look at the Specification at
40 // https://www.sonarsource.com/docs/CognitiveComplexity.pdf
41 // or user-facing docs at
42 // https://clang.llvm.org/extra/clang-tidy/checks/readability/function-cognitive-complexity.html
43 // Here are all the possible reasons:
44 enum Criteria : uint8_t {
45 None = 0U,
46
47 // B1, increases cognitive complexity (by 1)
48 // What causes it:
49 // * if, else if, else, ConditionalOperator (not BinaryConditionalOperator)
50 // * SwitchStmt
51 // * ForStmt, CXXForRangeStmt
52 // * WhileStmt, DoStmt
53 // * CXXCatchStmt
54 // * GotoStmt, IndirectGotoStmt (but not BreakStmt, ContinueStmt)
55 // * sequences of binary logical operators (BinOpLAnd, BinOpLOr)
56 // * each method in a recursion cycle (not implemented)
57 Increment = 1U << 0,
58
59 // B2, increases current nesting level (by 1)
60 // What causes it:
61 // * if, else if, else, ConditionalOperator (not BinaryConditionalOperator)
62 // * SwitchStmt
63 // * ForStmt, CXXForRangeStmt
64 // * WhileStmt, DoStmt
65 // * CXXCatchStmt
66 // * nested CXXConstructor, CXXDestructor, CXXMethod (incl. C++11 Lambda)
67 // * GNU Statement Expression
68 // * Apple Block declaration
69 IncrementNesting = 1U << 1,
70
71 // B3, increases cognitive complexity by the current nesting level
72 // Applied before IncrementNesting
73 // What causes it:
74 // * IfStmt, ConditionalOperator (not BinaryConditionalOperator)
75 // * SwitchStmt
76 // * ForStmt, CXXForRangeStmt
77 // * WhileStmt, DoStmt
78 // * CXXCatchStmt
79 PenalizeNesting = 1U << 2,
80
81 All = Increment | PenalizeNesting | IncrementNesting,
82
83 LLVM_MARK_AS_BITMASK_ENUM(PenalizeNesting),
84 };
85
86 // The helper struct used to record one increment occurrence, with all the
87 // details necessary.
88 struct Detail {
89 const SourceLocation Loc; // What caused the increment?
90 const unsigned short Nesting; // How deeply nested is Loc located?
91 const Criteria C; // The criteria of the increment
92
93 Detail(SourceLocation SLoc, unsigned short CurrentNesting, Criteria Crit)
94 : Loc(SLoc), Nesting(CurrentNesting), C(Crit) {}
95
96 // To minimize the sizeof(Detail), we only store the minimal info there.
97 // This function is used to convert from the stored info into the usable
98 // information - what message to output, how much of an increment did this
99 // occurrence actually result in.
100 std::pair<unsigned, unsigned short> process() const {
101 assert(C != Criteria::None && "invalid criteria");
102
103 unsigned MsgId = 0; // The id of the message to output.
104 unsigned short Increment = 0; // How much of an increment?
105
106 if (C == Criteria::All) {
107 Increment = 1 + Nesting;
108 MsgId = 0;
109 } else if (C == (Criteria::Increment | Criteria::IncrementNesting)) {
110 Increment = 1;
111 MsgId = 1;
112 } else if (C == Criteria::Increment) {
113 Increment = 1;
114 MsgId = 2;
115 } else if (C == Criteria::IncrementNesting) {
116 Increment = 0; // Unused in this message.
117 MsgId = 3;
118 } else {
119 llvm_unreachable("should not get to here.");
120 }
121
122 return {MsgId, Increment};
123 }
124 };
125
126 // Limit of 25 is the "upstream"'s default.
127 static constexpr unsigned DefaultLimit = 25U;
128
129 // Based on the publicly-available numbers for some big open-source projects
130 // https://sonarcloud.io/projects?languages=c%2Ccpp&size=5 we can estimate:
131 // value ~20 would result in no allocs for 98% of functions, ~12 for 96%, ~10
132 // for 91%, ~8 for 88%, ~6 for 84%, ~4 for 77%, ~2 for 64%, and ~1 for 37%.
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; // 25 elements is 200 bytes.
139 // Yes, 25 is a magic number. This is the seemingly-sane default for the
140 // upper limit for function cognitive complexity. Thus it would make sense
141 // to avoid allocations for any function that does not violate the limit.
142
143 // The grand total Cognitive Complexity of the function.
144 unsigned Total = 0;
145
146 // The function used to store new increment, calculate the total complexity.
147 void account(SourceLocation Loc, unsigned short Nesting, Criteria C);
148};
149
150} // namespace
151
152// All the possible messages that can be output. The choice of the message
153// to use is based of the combination of the CognitiveComplexity::Criteria.
154// It would be nice to have it in CognitiveComplexity struct, but then it is
155// not static.
156static constexpr std::array<StringRef, 4> Msgs = {{
157 // B1 + B2 + B3
158 "+%0, including nesting penalty of %1, nesting level increased to %2",
159
160 // B1 + B2
161 "+%0, nesting level increased to %2",
162
163 // B1
164 "+%0",
165
166 // B2
167 "nesting level increased to %2",
168}};
169
170void CognitiveComplexity::account(SourceLocation Loc, unsigned short Nesting,
171 Criteria C) {
172 C &= Criteria::All;
173 assert(C != Criteria::None && "invalid criteria");
174
175 Details.emplace_back(Loc, Nesting, C);
176 const Detail &D = Details.back();
177
178 const auto [MsgId, Increase] = D.process();
179
180 Total += Increase;
181}
182
183namespace {
184
185class FunctionASTVisitor final
186 : public RecursiveASTVisitor<FunctionASTVisitor> {
187 using Base = RecursiveASTVisitor<FunctionASTVisitor>;
188
189 // If set to true, macros are ignored during analysis.
190 const bool IgnoreMacros;
191
192 // The current nesting level (increased by Criteria::IncrementNesting).
193 unsigned short CurrentNestingLevel = 0;
194
195 // Used to efficiently know the last type of the binary sequence operator
196 // that was encountered. It would make sense for the function call to start
197 // the new sequence, thus it is a stack.
198 using OBO = std::optional<BinaryOperator::Opcode>;
199 std::stack<OBO, SmallVector<OBO, 4>> BinaryOperatorsStack;
200
201public:
202 explicit FunctionASTVisitor(const bool IgnoreMacros)
203 : IgnoreMacros(IgnoreMacros) {}
204
205 bool traverseStmtWithIncreasedNestingLevel(Stmt *Node) {
206 ++CurrentNestingLevel;
207 const bool ShouldContinue = Base::TraverseStmt(Node);
208 --CurrentNestingLevel;
209 return ShouldContinue;
210 }
211
212 bool traverseDeclWithIncreasedNestingLevel(Decl *Node) {
213 ++CurrentNestingLevel;
214 const bool ShouldContinue = Base::TraverseDecl(Node);
215 --CurrentNestingLevel;
216 return ShouldContinue;
217 }
218
219 bool TraverseIfStmt(IfStmt *Node, bool InElseIf = false) {
220 if (!Node)
221 return Base::TraverseIfStmt(Node);
222
223 {
224 CognitiveComplexity::Criteria Reasons =
225 CognitiveComplexity::Criteria::None;
226
227 // "If" increases cognitive complexity.
228 Reasons |= CognitiveComplexity::Criteria::Increment;
229 // "If" increases nesting level.
230 Reasons |= CognitiveComplexity::Criteria::IncrementNesting;
231
232 if (!InElseIf) {
233 // "If" receives a nesting increment commensurate with it's nested
234 // depth, if it is not part of "else if".
235 Reasons |= CognitiveComplexity::Criteria::PenalizeNesting;
236 }
237
238 CC.account(Node->getIfLoc(), CurrentNestingLevel, Reasons);
239 }
240
241 // If this IfStmt is *NOT* "else if", then only the body (i.e. "Then" and
242 // "Else") is traversed with increased Nesting level.
243 // However if this IfStmt *IS* "else if", then Nesting level is increased
244 // for the whole IfStmt (i.e. for "Init", "Cond", "Then" and "Else").
245
246 if (!InElseIf) {
247 if (!TraverseStmt(Node->getInit()))
248 return false;
249
250 if (!TraverseStmt(Node->getCond()))
251 return false;
252 } else {
253 if (!traverseStmtWithIncreasedNestingLevel(Node->getInit()))
254 return false;
255
256 if (!traverseStmtWithIncreasedNestingLevel(Node->getCond()))
257 return false;
258 }
259
260 // "Then" always increases nesting level.
261 if (!traverseStmtWithIncreasedNestingLevel(Node->getThen()))
262 return false;
263
264 if (!Node->getElse())
265 return true;
266
267 if (auto *E = dyn_cast<IfStmt>(Node->getElse()))
268 return TraverseIfStmt(E, true);
269
270 {
271 CognitiveComplexity::Criteria Reasons =
272 CognitiveComplexity::Criteria::None;
273
274 // "Else" increases cognitive complexity.
275 Reasons |= CognitiveComplexity::Criteria::Increment;
276 // "Else" increases nesting level.
277 Reasons |= CognitiveComplexity::Criteria::IncrementNesting;
278 // "Else" DOES NOT receive a nesting increment commensurate with it's
279 // nested depth.
280
281 CC.account(Node->getElseLoc(), CurrentNestingLevel, Reasons);
282 }
283
284 // "Else" always increases nesting level.
285 return traverseStmtWithIncreasedNestingLevel(Node->getElse());
286 }
287
288// The currently-being-processed stack entry, which is always the top.
289#define CurrentBinaryOperator BinaryOperatorsStack.top()
290
291 // In a sequence of binary logical operators, if the new operator is different
292 // from the previous one, then the cognitive complexity is increased.
293 bool TraverseBinaryOperator(BinaryOperator *Op) {
294 if (!Op || !Op->isLogicalOp())
295 return Base::TraverseBinaryOperator(Op);
296
297 // Make sure that there is always at least one frame in the stack.
298 if (BinaryOperatorsStack.empty())
299 BinaryOperatorsStack.emplace();
300
301 // If this is the first binary operator that we are processing, or the
302 // previous binary operator was different, there is an increment.
303 if (!CurrentBinaryOperator || Op->getOpcode() != CurrentBinaryOperator)
304 CC.account(Op->getOperatorLoc(), CurrentNestingLevel,
305 CognitiveComplexity::Criteria::Increment);
306
307 // We might encounter a function call, which starts a new sequence, thus
308 // we need to save the current previous binary operator.
309 const std::optional<BinaryOperator::Opcode> BinOpCopy(
311
312 // Record the operator that we are currently processing and traverse it.
313 CurrentBinaryOperator = Op->getOpcode();
314 const bool ShouldContinue = Base::TraverseBinaryOperator(Op);
315
316 // And restore the previous binary operator, which might be nonexistent.
317 CurrentBinaryOperator = BinOpCopy;
318
319 return ShouldContinue;
320 }
321
322 // It would make sense for the function call to start the new binary
323 // operator sequence, thus let's make sure that it creates a new stack frame.
324 bool TraverseCallExpr(CallExpr *Node) {
325 // If we are not currently processing any binary operator sequence, then
326 // no Node-handling is needed.
327 if (!Node || BinaryOperatorsStack.empty() || !CurrentBinaryOperator)
328 return Base::TraverseCallExpr(Node);
329
330 // Else, do add [uninitialized] frame to the stack, and traverse call.
331 BinaryOperatorsStack.emplace();
332 const bool ShouldContinue = Base::TraverseCallExpr(Node);
333 // And remove the top frame.
334 BinaryOperatorsStack.pop();
335
336 return ShouldContinue;
337 }
338
339#undef CurrentBinaryOperator
340
341 bool TraverseStmt(Stmt *Node) {
342 if (!Node)
343 return Base::TraverseStmt(Node);
344
345 if (IgnoreMacros && Node->getBeginLoc().isMacroID())
346 return true;
347
348 // Three following switch()'es have huge duplication, but it is better to
349 // keep them separate, to simplify comparing them with the Specification.
350
351 CognitiveComplexity::Criteria Reasons = CognitiveComplexity::Criteria::None;
352 SourceLocation Location = Node->getBeginLoc();
353
354 // B1. Increments
355 // There is an increment for each of the following:
356 switch (Node->getStmtClass()) {
357 // if, else if, else are handled in TraverseIfStmt(),
358 // FIXME: "each method in a recursion cycle" Increment is not implemented.
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;
369 break;
370 default:
371 // break LABEL, continue LABEL increase cognitive complexity,
372 // but they are not supported in C++ or C.
373 // Regular break/continue do not increase cognitive complexity.
374 break;
375 }
376
377 // B2. Nesting level
378 // The following structures increment the nesting level:
379 switch (Node->getStmtClass()) {
380 // if, else if, else are handled in TraverseIfStmt(),
381 // Nested methods and such are handled in TraverseDecl.
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;
392 break;
393 default:
394 break;
395 }
396
397 // B3. Nesting increments
398 // The following structures receive a nesting increment
399 // commensurate with their nested depth inside B2 structures:
400 switch (Node->getStmtClass()) {
401 // if, else if, else are handled in TraverseIfStmt().
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;
410 break;
411 default:
412 break;
413 }
414
415 if (Node->getStmtClass() == Stmt::ConditionalOperatorClass) {
416 // A little beautification.
417 // For conditional operator "cond ? true : false" point at the "?"
418 // symbol.
419 Location = cast<ConditionalOperator>(Node)->getQuestionLoc();
420 }
421
422 // If we have found any reasons, let's account it.
423 if (Reasons & CognitiveComplexity::Criteria::All)
424 CC.account(Location, CurrentNestingLevel, Reasons);
425
426 // Did we decide that the nesting level should be increased?
427 if (!(Reasons & CognitiveComplexity::Criteria::IncrementNesting))
428 return Base::TraverseStmt(Node);
429
430 return traverseStmtWithIncreasedNestingLevel(Node);
431 }
432
433 // The parameter MainAnalyzedFunction is needed to differentiate between the
434 // cases where TraverseDecl() is the entry point from
435 // FunctionCognitiveComplexityCheck::check() and the cases where it was called
436 // from the FunctionASTVisitor itself. Explanation: if we get a function
437 // definition (e.g. constructor, destructor, method), the Cognitive Complexity
438 // specification states that the Nesting level shall be increased. But if this
439 // function is the entry point, then the Nesting level should not be
440 // increased. Thus that parameter is there and is used to fall-through
441 // directly to traversing if this is the main function that is being analyzed.
442 bool TraverseDecl(Decl *Node, bool MainAnalyzedFunction = false) {
443 if (!Node || MainAnalyzedFunction)
444 return Base::TraverseDecl(Node);
445
446 // B2. Nesting level
447 // The following structures increment the nesting level:
448 switch (Node->getKind()) {
449 case Decl::Function:
450 case Decl::CXXMethod:
451 case Decl::CXXConstructor:
452 case Decl::CXXDestructor:
453 case Decl::Block:
454 break;
455 default:
456 // If this is something else, we use early return!
457 return Base::TraverseDecl(Node);
458 break;
459 }
460
461 CC.account(Node->getBeginLoc(), CurrentNestingLevel,
462 CognitiveComplexity::Criteria::IncrementNesting);
463
464 return traverseDeclWithIncreasedNestingLevel(Node);
465 }
466
467 CognitiveComplexity CC;
468};
469
470} // namespace
471
473 StringRef Name, ClangTidyContext *Context)
474 : ClangTidyCheck(Name, Context),
475 Threshold(Options.get("Threshold", CognitiveComplexity::DefaultLimit)),
476 DescribeBasicIncrements(Options.get("DescribeBasicIncrements", true)),
477 IgnoreMacros(Options.get("IgnoreMacros", false)) {}
478
481 Options.store(Opts, "Threshold", Threshold);
482 Options.store(Opts, "DescribeBasicIncrements", DescribeBasicIncrements);
483 Options.store(Opts, "IgnoreMacros", IgnoreMacros);
484}
485
487 Finder->addMatcher(
488 functionDecl(isDefinition(),
489 unless(anyOf(isDefaulted(), isDeleted(), isWeak())))
490 .bind("func"),
491 this);
492 Finder->addMatcher(lambdaExpr().bind("lambda"), this);
493}
494
496 const MatchFinder::MatchResult &Result) {
497 FunctionASTVisitor Visitor(IgnoreMacros);
498 SourceLocation Loc;
499
500 const auto *TheDecl = Result.Nodes.getNodeAs<FunctionDecl>("func");
501 const auto *TheLambdaExpr = Result.Nodes.getNodeAs<LambdaExpr>("lambda");
502 if (TheDecl) {
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);
508 } else {
509 Loc = TheLambdaExpr->getBeginLoc();
510 Visitor.TraverseLambdaExpr(const_cast<LambdaExpr *>(TheLambdaExpr));
511 }
512
513 if (Visitor.CC.Total <= Threshold)
514 return;
515
516 if (TheDecl)
517 diag(Loc, "function %0 has cognitive complexity of %1 (threshold %2)")
518 << TheDecl << Visitor.CC.Total << Threshold;
519 else
520 diag(Loc, "lambda has cognitive complexity of %0 (threshold %1)")
521 << Visitor.CC.Total << Threshold;
522
523 if (!DescribeBasicIncrements)
524 return;
525
526 // Output all the basic increments of complexity.
527 for (const auto &Detail : Visitor.CC.Details) {
528 auto [MsgId, Increase] = Detail.process();
529 assert(MsgId < Msgs.size() && "MsgId should always be valid");
530 // Increase, on the other hand, can be 0.
531
532 diag(Detail.Loc, Msgs[MsgId], DiagnosticIDs::Note)
533 << Increase << Detail.Nesting << 1 + Detail.Nesting;
534 }
535}
536
537} // namespace clang::tidy::readability
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
static constexpr std::array< StringRef, 4 > Msgs
llvm::StringMap< ClangTidyValue > OptionMap