Index: clang-tidy/readability/CMakeLists.txt =================================================================== --- clang-tidy/readability/CMakeLists.txt +++ clang-tidy/readability/CMakeLists.txt @@ -7,6 +7,7 @@ DeleteNullPointerCheck.cpp DeletedDefaultCheck.cpp ElseAfterReturnCheck.cpp + FunctionCognitiveComplexityCheck.cpp FunctionSizeCheck.cpp IdentifierNamingCheck.cpp ImplicitBoolConversionCheck.cpp Index: clang-tidy/readability/FunctionCognitiveComplexityCheck.h =================================================================== --- /dev/null +++ clang-tidy/readability/FunctionCognitiveComplexityCheck.h @@ -0,0 +1,44 @@ +//===--- FunctionCognitiveComplexityCheck.h - clang-tidy---------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_FUNCTION_COGNITIVE_COMPLEXITY_H +#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_FUNCTION_COGNITIVE_COMPLEXITY_H + +#include "../ClangTidy.h" + +namespace clang { +namespace tidy { +namespace readability { + +/// Checks function Cognitive Complexity metric. +/// +/// There is only one configuration option: +/// +/// * `Threshold` - flag functions with Cognitive Complexity exceeding +/// this number. The default is `25`. +/// +/// For the user-facing documentation see: +/// http://clang.llvm.org/extra/clang-tidy/checks/readability-function-cognitive-complexity.html +class FunctionCognitiveComplexityCheck : public ClangTidyCheck { +public: + FunctionCognitiveComplexityCheck(StringRef Name, ClangTidyContext *Context); + + void storeOptions(ClangTidyOptions::OptionMap &Opts) override; + void registerMatchers(ast_matchers::MatchFinder *Finder) override; + void check(const ast_matchers::MatchFinder::MatchResult &Result) override; + +private: + const unsigned Threshold; +}; + +} // namespace readability +} // namespace tidy +} // namespace clang + +#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_FUNCTION_COGNITIVE_COMPLEXITY_H Index: clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp =================================================================== --- /dev/null +++ clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp @@ -0,0 +1,629 @@ +//===--- FunctionCognitiveComplexityCheck.cpp - clang-tidy-----------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "FunctionCognitiveComplexityCheck.h" +#include "clang/AST/RecursiveASTVisitor.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang { +namespace tidy { +namespace readability { +namespace { + +struct CognitiveComplexity final { + /// Limit of 25 is the "upstream"'s default. + static constexpr unsigned DefaultLimit = 25U; + + /// Any increment is based on some combination of reasons. + /// For details you can look at the Specification at + /// https://www.sonarsource.com/docs/CognitiveComplexity.pdf + /// or user-facing docs at + /// http://clang.llvm.org/extra/clang-tidy/checks/readability-function-cognitive-complexity.html + /// Here are all the possible reasons: + enum Criteria : unsigned char { + None = 0U, + + /// B1, increases cognitive complexity (by 1) + /// What causes it: + /// * if, else if, else, ConditionalOperator (not BinaryConditionalOperator) + /// * SwitchStmt + /// * ForStmt, CXXForRangeStmt + /// * WhileStmt, DoStmt + /// * CXXCatchStmt + /// * GotoStmt (but not BreakStmt, ContinueStmt) + /// * sequences of binary logical operators (BinOpLAnd, BinOpLOr) + /// * each method in a recursion cycle (not implemented) + Increment = 1U << 0, + + /// B2, increases current nesting level (by 1) + /// What causes it: + /// * if, else if, else, ConditionalOperator (not BinaryConditionalOperator) + /// * SwitchStmt + /// * ForStmt, CXXForRangeStmt + /// * WhileStmt, DoStmt + /// * CXXCatchStmt + /// * nested CXXConstructor, CXXDestructor, CXXMethod (incl. C++11 Lambda) + IncrementNesting = 1U << 1, + + /// B3, increases cognitive complexity by the current nesting level + /// Applied before IncrementNesting + /// What causes it: + /// * IfStmt, ConditionalOperator (not BinaryConditionalOperator) + /// * SwitchStmt + /// * ForStmt, CXXForRangeStmt + /// * WhileStmt, DoStmt + /// * CXXCatchStmt + PenalizeNesting = 1U << 2, + + All = Increment | PenalizeNesting | IncrementNesting, + }; + + /// All the possible messages that can be outputed. The choice of the message + /// to use is based of the combination of the Criterias + static const std::array Msgs; + + /// The helper struct used to record one increment occurence, with all the + /// details nessesary + struct Detail final { + const SourceLocation Loc; /// What caused the increment? + const unsigned short Nesting; /// How deeply nested is Loc located? + const Criteria C : 3; /// The criteria of the increment + + /// Criteria C is a bitfield. Even though Criteria is an unsigned char; and + /// only using 3 bits will still result in padding, the fact that it is a + /// bitfield is a reminder that it is important to min(sizeof(Detail)) + + Detail(SourceLocation SLoc, unsigned short CurrentNesting, Criteria Crit) + : Loc(SLoc), Nesting(CurrentNesting), C(Crit) {} + + /// To minimize the sizeof(Detail), we only store the minimal info there. + /// This function is used to convert from the stored info into the usable + /// information - what message to output, how much of an increment did this + /// occurence actually result in + std::pair process() const { + assert(C != Criteria::None && "invalid criteria"); + + const char *Msg; /// The message to output + unsigned short Increment; /// How much of an increment? + + if (C == Criteria::All) { + Increment = 1 + Nesting; + Msg = Msgs[0]; + } else if (C == (Criteria::Increment | Criteria::IncrementNesting)) { + Increment = 1; + Msg = Msgs[1]; + } else if (C == Criteria::Increment) { + Increment = 1; + Msg = Msgs[2]; + } else if (C == Criteria::IncrementNesting) { + Increment = 0; /// Unused in this message. + Msg = Msgs[3]; + } else + llvm_unreachable("should not get to here."); + + return std::make_pair(Msg, Increment); + } + }; + // static_assert(sizeof(Detail) <= 8, "it's best to keep the size minimal"); + + /// Based on the publicly-avaliable numbers for some big open-source projects + /// https://sonarcloud.io/projects?languages=c%2Ccpp&size=5 we can estimate: + /// value ~20 would result in no allocs for 98% of functions, ~12 for 96%, ~10 + /// for 91%, ~8 for 88%, ~6 for 84%, ~4 for 77%, ~2 for 64%, and ~1 for 37% + SmallVector Details; // 25 elements is 200 bytes. + /// Yes, 25 is a magic number. This is the seemingly-sane default for the + /// upper limit for function cognitive complexity. Thus it would make sense + /// to avoid allocations for any function that does not violate the limit. + + /// The grand total Cognitive Complexity of the function + unsigned Total = 0; + + /// The function used to store new increment, calculate the total complexity + void account(SourceLocation Loc, unsigned short Nesting, Criteria C); +}; + +/// Refer to the enum Criteria for detailed explaination. +const std::array CognitiveComplexity::Msgs = {{ + /// B1 + B2 + B3 + "+%0, including nesting penalty of %1, nesting level increased to %2", + + /// B1 + B2 + "+%0, nesting level increased to %2", + + /// B1 + "+%0", + + /// B2 + "nesting level increased to %2", +}}; + +/// Criteria is a bitset, thus a few helpers are needed +CognitiveComplexity::Criteria operator|(CognitiveComplexity::Criteria LHS, + CognitiveComplexity::Criteria RHS) { + return static_cast( + static_cast::type>( + LHS) | + static_cast::type>( + RHS)); +} +CognitiveComplexity::Criteria operator&(CognitiveComplexity::Criteria LHS, + CognitiveComplexity::Criteria RHS) { + return static_cast( + static_cast::type>( + LHS) & + static_cast::type>( + RHS)); +} +CognitiveComplexity::Criteria &operator|=(CognitiveComplexity::Criteria &LHS, + CognitiveComplexity::Criteria RHS) { + LHS = operator|(LHS, RHS); + return LHS; +} +CognitiveComplexity::Criteria &operator&=(CognitiveComplexity::Criteria &LHS, + CognitiveComplexity::Criteria RHS) { + LHS = operator&(LHS, RHS); + return LHS; +} + +void CognitiveComplexity::account(SourceLocation Loc, unsigned short Nesting, + Criteria C) { + C &= Criteria::All; + assert(C != Criteria::None && "invalid criteria"); + + Details.emplace_back(Loc, Nesting, C); + const Detail &D(Details.back()); + + const std::pair Reasoning(D.process()); + Total += Reasoning.second; +} + +class FunctionASTVisitor final + : public RecursiveASTVisitor { + using Base = RecursiveASTVisitor; + + /// The current nesting level (increased by Criteria::IncrementNesting) + unsigned short CurrentNestingLevel = 0; + + /// Used to efficiently know the last type of binary sequence operator that + /// was encountered. It would make sense for the function call to start the + /// new sequence, thus it is a stack. + std::stack, + SmallVector, 4>> + BinaryOperatorsStack; + +public: + /// Important piece of the information: the Nesting level is increased only + /// for the body of whatever statement, not it's init/cond/inc, thus the + /// common repetitive code is factored here. +#define TraverseWithIncreasedNestingLevel(CLASS, Node) \ + ++CurrentNestingLevel; \ + ShouldContinue = Base::Traverse##CLASS(Node); \ + --CurrentNestingLevel; + +#define IncreasesNestingLevel(CLASS) \ + bool Traverse##CLASS(CLASS *Node) { \ + if (!Node) \ + return Base::Traverse##CLASS(Node); \ + \ + bool ShouldContinue; \ + TraverseWithIncreasedNestingLevel(CLASS, Node); \ + \ + return ShouldContinue; \ + } + + /// B2. Nesting level + /// The following structures increment the nesting level: + IncreasesNestingLevel(DefaultStmt); + IncreasesNestingLevel(CXXCatchStmt); + /// Other instances are more complex, and need standalone functions + +#undef IncreasesNestingLevel + + bool TraverseIfStmt(IfStmt *Node, bool InElseIf = false) { + if (!Node) + return Base::TraverseIfStmt(Node); + + { + CognitiveComplexity::Criteria Reasons = + CognitiveComplexity::Criteria::None; + + /// if increases cognitive complexity + Reasons |= CognitiveComplexity::Criteria::Increment; + /// if increases nesting level + Reasons |= CognitiveComplexity::Criteria::IncrementNesting; + + /// if receives a nesting increment commensurate with it's nested depth + /// but only if it is not part of else if + if (!InElseIf) + Reasons |= CognitiveComplexity::Criteria::PenalizeNesting; + + CC.account(Node->getIfLoc(), CurrentNestingLevel, Reasons); + } + + bool ShouldContinue = TraverseStmt(Node->getInit()); + if (!ShouldContinue) + return ShouldContinue; + + ShouldContinue = TraverseStmt(Node->getCond()); + if (!ShouldContinue) + return ShouldContinue; + + /// if increases nesting level + TraverseWithIncreasedNestingLevel(Stmt, Node->getThen()); + + if (!ShouldContinue || !Node->getElse()) + return ShouldContinue; + + /// else OR else if increases cognitive complexity and nesting level + /// but else if does NOT result in double increase ! + if (isa(Node->getElse())) + return TraverseIfStmt(dyn_cast(Node->getElse()), true); + + { + CognitiveComplexity::Criteria Reasons = + CognitiveComplexity::Criteria::None; + + /// else increases cognitive complexity + Reasons |= CognitiveComplexity::Criteria::Increment; + /// else increases nesting level + Reasons |= CognitiveComplexity::Criteria::IncrementNesting; + /// else DOES NOT receive a nesting increment commensurate with it's + /// nested depth + + CC.account(Node->getElseLoc(), CurrentNestingLevel, Reasons); + } + + TraverseWithIncreasedNestingLevel(Stmt, Node->getElse()); + + return ShouldContinue; + } + + bool TraverseConditionalOperator(ConditionalOperator *Node) { + if (!Node) + return Base::TraverseConditionalOperator(Node); + + bool ShouldContinue = TraverseStmt(Node->getCond()); + if (!ShouldContinue) + return ShouldContinue; + + TraverseWithIncreasedNestingLevel(Stmt, Node->getLHS()); + + if (!ShouldContinue) + return ShouldContinue; + + TraverseWithIncreasedNestingLevel(Stmt, Node->getRHS()); + + return ShouldContinue; + } + + bool TraverseCaseStmt(CaseStmt *Node) { + if (!Node) + return Base::TraverseCaseStmt(Node); + + bool ShouldContinue = TraverseStmt(Node->getLHS()); + if (!ShouldContinue) + return ShouldContinue; + + ShouldContinue = TraverseStmt(Node->getRHS()); + if (!ShouldContinue) + return ShouldContinue; + + TraverseWithIncreasedNestingLevel(Stmt, Node->getSubStmt()); + + return ShouldContinue; + } + + bool TraverseForStmt(ForStmt *Node) { + if (!Node) + return Base::TraverseForStmt(Node); + + bool ShouldContinue = TraverseStmt(Node->getInit()); + if (!ShouldContinue) + return ShouldContinue; + + ShouldContinue = TraverseStmt(Node->getCond()); + if (!ShouldContinue) + return ShouldContinue; + + ShouldContinue = TraverseStmt(Node->getInc()); + if (!ShouldContinue) + return ShouldContinue; + + TraverseWithIncreasedNestingLevel(Stmt, Node->getBody()); + + return ShouldContinue; + } + + bool TraverseCXXForRangeStmt(CXXForRangeStmt *Node) { + if (!Node) + return Base::TraverseCXXForRangeStmt(Node); + + bool ShouldContinue = TraverseDecl(Node->getLoopVariable()); + if (!ShouldContinue) + return ShouldContinue; + + ShouldContinue = TraverseStmt(Node->getRangeInit()); + if (!ShouldContinue) + return ShouldContinue; + + TraverseWithIncreasedNestingLevel(Stmt, Node->getBody()); + + return ShouldContinue; + } + + bool TraverseWhileStmt(WhileStmt *Node) { + if (!Node) + return Base::TraverseWhileStmt(Node); + + bool ShouldContinue = TraverseStmt(Node->getCond()); + if (!ShouldContinue) + return ShouldContinue; + + TraverseWithIncreasedNestingLevel(Stmt, Node->getBody()); + + return ShouldContinue; + } + + bool TraverseDoStmt(DoStmt *Node) { + if (!Node) + return Base::TraverseDoStmt(Node); + + bool ShouldContinue = TraverseStmt(Node->getCond()); + if (!ShouldContinue) + return ShouldContinue; + + TraverseWithIncreasedNestingLevel(Stmt, Node->getBody()); + + return ShouldContinue; + } + +/// The currently-being-processed stack entry, which is always the top +#define CurrentBinaryOperator BinaryOperatorsStack.top() + +#define TraverseBinOp(CLASS) \ + bool TraverseBin##CLASS(BinaryOperator *Op) { \ + if (!Op) \ + return Base::TraverseBin##CLASS(Op); \ + \ + /** Make sure that there is always at least one frame in the stack */ \ + if (BinaryOperatorsStack.empty()) \ + BinaryOperatorsStack.emplace(); \ + \ + /** If this is the first binary operator that we are processing, or the \ + ** previous binary operator was different, there is an increment */ \ + if (!CurrentBinaryOperator || Op->getOpcode() != CurrentBinaryOperator) \ + CC.account(Op->getOperatorLoc(), CurrentNestingLevel, \ + CognitiveComplexity::Criteria::Increment); \ + \ + /** We might encounter function call, which starts a new sequence, thus \ + ** we need to save the current previous binary operator */ \ + const Optional BinOpCopy(CurrentBinaryOperator); \ + \ + /** Record the operator that we are currently processing and traverse it \ + */ \ + CurrentBinaryOperator = Op->getOpcode(); \ + const bool ShouldContinue = Base::TraverseBin##CLASS(Op); \ + /** And restore the previous binary operator, which might be nonexistant \ + */ \ + CurrentBinaryOperator = BinOpCopy; \ + \ + return ShouldContinue; \ + } + + /// In a sequence of binary logical operators, if new operator is different + /// from the previous-one, then the cognitive complexity is increased. + TraverseBinOp(LAnd); + TraverseBinOp(LOr); + +#define TraverseCallExpr_(CLASS) \ + bool Traverse##CLASS(CLASS *Call) { \ + /** If we are not currently processing any binary operator sequence, then \ + ** no special-handling is needed */ \ + if (!Call || BinaryOperatorsStack.empty() || !CurrentBinaryOperator) \ + return Base::Traverse##CLASS(Call); \ + \ + /** Else, do add [uninitialized] frame to the stack, and traverse call */ \ + BinaryOperatorsStack.emplace(); \ + const bool ShouldContinue = Base::Traverse##CLASS(Call); \ + /** And remove the top frame */ \ + BinaryOperatorsStack.pop(); \ + \ + return ShouldContinue; \ + } + + /// It would make sense for the function call to start the new binary + /// operator sequence, thus let's make sure that it creates new stack frame + TraverseCallExpr_(CallExpr); + TraverseCallExpr_(CXXMemberCallExpr); + TraverseCallExpr_(CXXOperatorCallExpr); + + bool TraverseStmt(Stmt *Node) { + if (!Node) + return Base::TraverseStmt(Node); + + /// Three following switch()'es have huge duplication, but it is better to + /// keep them separate, to simplify comparing them with the Specification + + CognitiveComplexity::Criteria Reasons = CognitiveComplexity::Criteria::None; + SourceLocation Location = Node->getLocStart(); + + /// B1. Increments + /// There is an increment for each of the following: + switch (Node->getStmtClass()) { + /// if, else if, else are handled in TraverseIfStmt() + /// FIXME: each method in a recursion cycle + case Stmt::ConditionalOperatorClass: + case Stmt::SwitchStmtClass: + case Stmt::ForStmtClass: + case Stmt::CXXForRangeStmtClass: + case Stmt::WhileStmtClass: + case Stmt::DoStmtClass: + case Stmt::CXXCatchStmtClass: + case Stmt::GotoStmtClass: + Reasons |= CognitiveComplexity::Criteria::Increment; + break; + default: + /// break LABEL, continue LABEL increase cognitive complexity, + /// but they are not supported in C++ or C. + /// regular break/continue do not increase cognitive complexity + break; + } + + /// B2. Nesting level + /// The following structures increment the nesting level: + switch (Node->getStmtClass()) { + /// if, else if, else are handled in TraverseIfStmt() + /// nested methods and such are handled in TraverseDecl + case Stmt::ConditionalOperatorClass: + case Stmt::SwitchStmtClass: + case Stmt::ForStmtClass: + case Stmt::CXXForRangeStmtClass: + case Stmt::WhileStmtClass: + case Stmt::DoStmtClass: + case Stmt::CXXCatchStmtClass: + Reasons |= CognitiveComplexity::Criteria::IncrementNesting; + break; + default: + break; + } + + /// B3. Nesting increments + /// The following structures receive a nesting increment + /// commensurate with their nested depth inside B2 structures: + switch (Node->getStmtClass()) { + /// if, else if, else are handled in TraverseIfStmt() + case Stmt::ConditionalOperatorClass: + case Stmt::SwitchStmtClass: + case Stmt::ForStmtClass: + case Stmt::CXXForRangeStmtClass: + case Stmt::WhileStmtClass: + case Stmt::DoStmtClass: + case Stmt::CXXCatchStmtClass: + Reasons |= CognitiveComplexity::Criteria::PenalizeNesting; + break; + default: + break; + } + + if (Node->getStmtClass() == Stmt::ConditionalOperatorClass) { + /// A little beautification. + /// For conditional operator "cond ? true : false" point at the "?" + /// symbol. + ConditionalOperator *COp = dyn_cast(Node); + Location = COp->getQuestionLoc(); + } + + /// if we have found any reasons, let's account it. + if (Reasons & CognitiveComplexity::Criteria::All) + CC.account(Location, CurrentNestingLevel, Reasons); + + return Base::TraverseStmt(Node); + } + + /// The second non-standard parameter MainAnalyzedFunction is needed to + /// differentiate between the cases where TraverseDecl() is the entry point + /// from FunctionCognitiveComplexityCheck::check() and the cases where it was + /// called from the FunctionASTVisitor itself. + /// Explaination: if we get a function definition (e.g. constructor, + /// destructor, method), the Cognitive Complexity specification states that + /// the Nesting level shall be increased. But if this function is the entry + /// point, then the Nesting level should not be increased. Thus that parameter + /// is there and is used to fall-through directly to traversing if this is + /// the main function that is being analyzed. + bool TraverseDecl(Decl *Node, bool MainAnalyzedFunction = false) { + if (!Node || MainAnalyzedFunction) + return Base::TraverseDecl(Node); + + /// B2. Nesting level + /// The following structures increment the nesting level: + switch (Node->getKind()) { + /// lambda is handled in TraverseLambdaExpr(). + /// can't have nested functions, so not accounted for + case Decl::CXXConstructor: + case Decl::CXXDestructor: + case Decl::CXXMethod: + break; + default: + return Base::TraverseDecl(Node); + break; + } + + CC.account(Node->getLocStart(), CurrentNestingLevel, + CognitiveComplexity::Criteria::IncrementNesting); + + bool ShouldContinue; + TraverseWithIncreasedNestingLevel(Decl, Node); + + return ShouldContinue; + } + + bool TraverseLambdaExpr(LambdaExpr *Node) { + if (!Node) + return Base::TraverseLambdaExpr(Node); + + CC.account(Node->getLocStart(), CurrentNestingLevel, + CognitiveComplexity::Criteria::IncrementNesting); + + bool ShouldContinue; + TraverseWithIncreasedNestingLevel(LambdaExpr, Node); + + return ShouldContinue; + } + + CognitiveComplexity CC; +}; +} // namespace + +FunctionCognitiveComplexityCheck::FunctionCognitiveComplexityCheck( + StringRef Name, ClangTidyContext *Context) + : ClangTidyCheck(Name, Context), + Threshold(Options.get("Threshold", CognitiveComplexity::DefaultLimit)) {} + +void FunctionCognitiveComplexityCheck::storeOptions( + ClangTidyOptions::OptionMap &Opts) { + Options.store(Opts, "Threshold", Threshold); +} + +void FunctionCognitiveComplexityCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + functionDecl(unless(anyOf(isInstantiated(), isImplicit()))).bind("func"), + this); +} + +void FunctionCognitiveComplexityCheck::check( + const MatchFinder::MatchResult &Result) { + const auto *Func = Result.Nodes.getNodeAs("func"); + + FunctionASTVisitor Visitor; + Visitor.TraverseDecl(const_cast(Func), true); + + if (Visitor.CC.Total <= Threshold) + return; + + diag(Func->getLocation(), + "function %0 has cognitive complexity of %1 (threshold %2)") + << Func << Visitor.CC.Total << Threshold; + + for (const auto &Detail : Visitor.CC.Details) { + const char *IncreaseMessage = nullptr; + unsigned short Increase = 0; + std::tie(IncreaseMessage, Increase) = Detail.process(); + assert(IncreaseMessage && "the code should always provide a msg"); + /// Increase, on the other hand, can be 0, if only nesting is increased. + + diag(Detail.Loc, IncreaseMessage, DiagnosticIDs::Note) + << Increase << Detail.Nesting << 1 + Detail.Nesting; + } +} + +} // namespace readability +} // namespace tidy +} // namespace clang Index: clang-tidy/readability/ReadabilityTidyModule.cpp =================================================================== --- clang-tidy/readability/ReadabilityTidyModule.cpp +++ clang-tidy/readability/ReadabilityTidyModule.cpp @@ -16,6 +16,7 @@ #include "DeleteNullPointerCheck.h" #include "DeletedDefaultCheck.h" #include "ElseAfterReturnCheck.h" +#include "FunctionCognitiveComplexityCheck.h" #include "FunctionSizeCheck.h" #include "IdentifierNamingCheck.h" #include "ImplicitBoolConversionCheck.h" @@ -55,6 +56,8 @@ "readability-deleted-default"); CheckFactories.registerCheck( "readability-else-after-return"); + CheckFactories.registerCheck( + "readability-function-cognitive-complexity"); CheckFactories.registerCheck( "readability-function-size"); CheckFactories.registerCheck( Index: docs/ReleaseNotes.rst =================================================================== --- docs/ReleaseNotes.rst +++ docs/ReleaseNotes.rst @@ -137,6 +137,12 @@ Checks if the required file flag ``IN_CLOEXEC`` is present in the argument of ``inotify_init1()``. +- New `readability-function-cognitive-complexity + `_ check + + For each function, calculates Cognitive Complexity metric, and flags the + functions with that metric exceeding the configured limit. + - New `readability-static-accessed-through-instance `_ check Index: docs/clang-tidy/checks/list.rst =================================================================== --- docs/clang-tidy/checks/list.rst +++ docs/clang-tidy/checks/list.rst @@ -186,6 +186,7 @@ readability-delete-null-pointer readability-deleted-default readability-else-after-return + readability-function-cognitive-complexity readability-function-size readability-identifier-naming readability-implicit-bool-conversion Index: docs/clang-tidy/checks/readability-function-cognitive-complexity.rst =================================================================== --- /dev/null +++ docs/clang-tidy/checks/readability-function-cognitive-complexity.rst @@ -0,0 +1,124 @@ +.. title:: clang-tidy - readability-function-cognitive-complexity + +readability-function-cognitive-complexity +========================================= + +Checks function Cognitive Complexity metric. + +The metric is implemented as per `COGNITIVE COMPLEXITY by SonarSource +`_ specification +version 1.2 (19 April 2017). + +Options +------- + +.. option:: Threshold + + Flag functions with Cognitive Complexity exceeding this number. + The default is `25`. + +Building blocks +--------------- + +There are three basic building blocks of a Cognitive Complexity metric: + +Increment +^^^^^^^^^ + +The following structures increase the function's Cognitive Complexity metric +(by 1): + * Conditional operators: + * `if()` + * `else if()` + * `else` + * `cond ? true : false` + * `switch()` + * Loops: + * `for() + * C++11 range-based `for()` + * `while()` + * `do while()` + * `catch () {}` + * `goto LABEL` + * sequences of binary logical operators: + * `boolean1 || boolean2` + * `boolean1 && boolean2` + +Nesting level +^^^^^^^^^^^^^ + +While by itself the nesting level not change the function's Cognitive Complexity +metric, it is tracked, and is used by the next, third building block. +The following structures increase the nesting level (by 1): + * Conditional operators: + * `if()` + * `else if()` + * `else` + * `cond ? true : false` + * `switch()` + * Loops: + * `for() + * C++11 range-based `for()` + * `while()` + * `do while()` + * `catch () {}` + * Nested functions: + * C++11 Lambda + * Nested `class` + * Nested `struct` + +Nesting increment +^^^^^^^^^^^^^^^^^ + +And this is where the previous basic building block, `Nesting level`_, matters. +The following structures increase the function's Cognitive Complexity metric by +the current `Nesting level`_: + * Conditional operators: + * `if()` + * `cond ? true : false` + * `switch()` + * Loops: + * `for() + * C++11 range-based `for()` + * `while()` + * `do while()` + * `catch () {}` + +Examples +-------- + +The simplest case. This function has Cognitive complexity of 0. +``` +void function0() {} +``` + +Slightly better example. This function has Cognitive complexity of 1. +``` +int function1(bool var) { + if(var) // +1 + return 42; + return 0; +} +``` + +Full example. This function has Cognitive complexity of 3. +``` +int function3(bool var1, bool var2) { + if(var1) { // +1, nesting level +1 + if(var2) // +2 (1 + current nesting level of 1) + return 42; + } + + return 0; +} +``` + +Limitations +----------- + +The metric is implemented with two notable exceptions: + * `preprocessor conditionals` (`#ifdef`, `#if`, `#elif`, `#else`, `#endif`) + are not accounted for. Could be done. + * `each method in a recursion cycle` is not accounted for. It can't be fully + implemented, because cross-translational-unit analysis would be needed, + which is currently not possible in clang-tidy. Index: test/clang-tidy/readability-function-cognitive-complexity.cpp =================================================================== --- /dev/null +++ test/clang-tidy/readability-function-cognitive-complexity.cpp @@ -0,0 +1,839 @@ +// RUN: %check_clang_tidy %s readability-function-cognitive-complexity %t -- -config='{CheckOptions: [{key: readability-function-cognitive-complexity.Threshold, value: 0}]}' -- -std=c++11 + +// any function should be checked. + +extern int ext_func(int x = 0); + +int some_func(int x = 0); + +static int some_other_func(int x = 0) {} + +template void some_templ_func(T x = 0) {} + +class SomeClass { +public: + int *begin(int x = 0); + int *end(int x = 0); + static int func(int x = 0); + template void some_templ_func(T x = 0) {} +}; + +// nothing ever decreases cognitive complexity, so we can check all the things +// in one go. none of the following should increase cognitive complexity: +void unittest_false() { + {}; + ext_func(); + some_func(); + some_other_func(); + some_templ_func(); + some_templ_func(); + SomeClass::func(); + SomeClass C; + C.some_templ_func(); + C.some_templ_func(); + C.func(); + C.end(); + int i = some_func(); + i = i; + i++; + --i; + i < 0; + int j = 0 ?: 1; + auto k = new int; + delete k; + throw i; + { + throw i; + } +end: + return; +} + +#if 1 +#define CC100 +#else +// this macro has cognitive complexity of 100. +// it is needed to be able to compare the testcases with the +// reference Sonar implementation. please place it right after the first +// CHECK-NOTES in each function +#define CC100 if(1){if(1){if(1){if(1){if(1){if(1){if(1){if(1){if(1){if(1){if(1){if(1){if(1){}}}}}if(1){}}}}}}}}} +#endif + +//----------------------------------------------------------------------------// +//------------------------------ B1. Increments ------------------------------// +//----------------------------------------------------------------------------// +// Check that every thing listed in B1 of the specification does indeed // +// recieve the base increment, and that not-body does not increase nesting // +//----------------------------------------------------------------------------// + +// break does not increase cognitive complexity. +// only break LABEL does, but it is unavaliable in C or C++ + +// continue does not increase cognitive complexity. +// only continue LABEL does, but it is unavaliable in C or C++ + +void unittest_b1_00() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b1_00' has cognitive complexity of 5 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + if (1 ? 1 : 0) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:9: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } else if (1 ? 1 : 0) { +// CHECK-NOTES: :[[@LINE-1]]:10: note: +1, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:16: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } else { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +1, nesting level increased to 1{{$}} + } +} + +void unittest_b1_01() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b1_01' has cognitive complexity of 2 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + int i = (1 ? 1 : 0) ? 1 : 0; +// CHECK-NOTES: :[[@LINE-1]]:23: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:14: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +} + +void unittest_b1_02(int x) { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b1_02' has cognitive complexity of 5 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + switch (1 ? 1 : 0) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:13: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + case -1: + return; + case 1 ? 1 : 0: +// CHECK-NOTES: :[[@LINE-1]]:10: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + return; + case (1 ? 2 : 0) ... (1 ? 3 : 0): +// CHECK-NOTES: :[[@LINE-1]]:11: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:27: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + return; + default: + break; + } +} + +void unittest_b1_03(int x) { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b1_03' has cognitive complexity of 4 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + for (x = 1 ? 1 : 0; x < (1 ? 1 : 0); x += 1 ? 1 : 0) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:14: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-3]]:30: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-4]]:47: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + break; + continue; + } +} + +void unittest_b1_04() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b1_04' has cognitive complexity of 2 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + SomeClass C; + for (int i : (1 ? C : C)) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:19: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + break; + continue; + } +} + +void unittest_b1_05() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b1_05' has cognitive complexity of 2 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + while (1 ? 1 : 0) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:12: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + break; + continue; + } +} + +void unittest_b1_06() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b1_06' has cognitive complexity of 2 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + do { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + break; + continue; + } while (1 ? 1 : 0); +// CHECK-NOTES: :[[@LINE-1]]:14: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +} + +void unittest_b1_07() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b1_07' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } +} + +void unittest_b1_08() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b1_08' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + goto end; +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1{{$}} +end: + return; +} + +void unittest_b1_09_00() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b1_09_00' has cognitive complexity of 34 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + if(1 && 1) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:8: note: +1{{$}} + } + if(1 && 1 && 1) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:13: note: +1{{$}} + } + if((1 && 1) && 1) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:15: note: +1{{$}} + } + if(1 && (1 && 1)) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:8: note: +1{{$}} + } + + if(1 && 1 || 1) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:13: note: +1{{$}} +// CHECK-NOTES: :[[@LINE-3]]:8: note: +1{{$}} + } + if((1 && 1) || 1) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:15: note: +1{{$}} +// CHECK-NOTES: :[[@LINE-3]]:9: note: +1{{$}} + } + if(1 && (1 || 1)) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:8: note: +1{{$}} +// CHECK-NOTES: :[[@LINE-3]]:14: note: +1{{$}} + } + + if(1 || 1) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:8: note: +1{{$}} + } + if(1 || 1 || 1) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:13: note: +1{{$}} + } + if((1 || 1) || 1) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:15: note: +1{{$}} + } + if(1 || (1 || 1)) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:8: note: +1{{$}} + } + + if(1 || 1 && 1) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:8: note: +1{{$}} +// CHECK-NOTES: :[[@LINE-3]]:13: note: +1{{$}} + } + if((1 || 1) && 1) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:15: note: +1{{$}} +// CHECK-NOTES: :[[@LINE-3]]:9: note: +1{{$}} + } + if(1 || (1 && 1)) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:8: note: +1{{$}} +// CHECK-NOTES: :[[@LINE-3]]:14: note: +1{{$}} + } +} + +void unittest_b1_09_01() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b1_09_01' has cognitive complexity of 12 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + if(1 && some_func(1 && 1)) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:8: note: +1{{$}} +// CHECK-NOTES: :[[@LINE-3]]:23: note: +1{{$}} + } + if(1 && some_func(1 || 1)) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:8: note: +1{{$}} +// CHECK-NOTES: :[[@LINE-3]]:23: note: +1{{$}} + } + if(1 || some_func(1 || 1)) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:8: note: +1{{$}} +// CHECK-NOTES: :[[@LINE-3]]:23: note: +1{{$}} + } + if(1 || some_func(1 && 1)) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:8: note: +1{{$}} +// CHECK-NOTES: :[[@LINE-3]]:23: note: +1{{$}} + } +} + +// FIXME: each method in a recursion cycle + +//----------------------------------------------------------------------------// +//---------------------------- B2. Nesting lebel -----------------------------// +//----------------------------------------------------------------------------// +// Check that every thing listed in B2 of the specification does indeed // +// increase the nesting level // +//----------------------------------------------------------------------------// + +void unittest_b2_00() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b2_00' has cognitive complexity of 9 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + if(true) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } else if (true) { +// CHECK-NOTES: :[[@LINE-1]]:10: note: +1, nesting level increased to 1{{$}} + if(true) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } else { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +1, nesting level increased to 1{{$}} + if(true) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } +} + +void unittest_b2_01() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b2_01' has cognitive complexity of 5 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + int i = 1 ? (1 ? 1 : 0) : (1 ? 1 : 0); +// CHECK-NOTES: :[[@LINE-1]]:13: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} +// CHECK-NOTES: :[[@LINE-2]]:18: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} +// CHECK-NOTES: :[[@LINE-3]]:32: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} +// FIXME: would be nice to point at the '?' symbol. does not seem to be possible +} + +void unittest_b2_02(int x) { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b2_02' has cognitive complexity of 3 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + switch (x) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + case -1: + if(true) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + return; + default: + return; + } +} + +void unittest_b2_03() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b2_03' has cognitive complexity of 3 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + for (;;) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + if(true) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } +} + +void unittest_b2_04() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b2_04' has cognitive complexity of 3 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + SomeClass C; + for (int i : C) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + if(true) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } +} + +void unittest_b2_05() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b2_05' has cognitive complexity of 3 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + while (true) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + if(true) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } +} + +void unittest_b2_06() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b2_06' has cognitive complexity of 3 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + do { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + if(true) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } while (true); +} + +void unittest_b2_07() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b2_07' has cognitive complexity of 3 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + if(true) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } +} + +void unittest_b2_08_00() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b2_08_00' has cognitive complexity of 8 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + class X { + X() { +// CHECK-NOTES: :[[@LINE-1]]:5: note: nesting level increased to 1{{$}} + CC100; + + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } + + ~X() { +// CHECK-NOTES: :[[@LINE-1]]:5: note: nesting level increased to 1{{$}} + CC100; + + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } + + void Y() { +// CHECK-NOTES: :[[@LINE-1]]:5: note: nesting level increased to 1{{$}} + CC100; + + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } + + static void Z() { +// CHECK-NOTES: :[[@LINE-1]]:5: note: nesting level increased to 1{{$}} + CC100; + + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } + +// CHECK-NOTES: :[[@LINE-36]]:5: warning: function 'X' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] +// CHECK-NOTES: :[[@LINE-33]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + +// CHECK-NOTES: :[[@LINE-30]]:5: warning: function '~X' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] +// CHECK-NOTES: :[[@LINE-27]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + +// CHECK-NOTES: :[[@LINE-24]]:10: warning: function 'Y' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] +// CHECK-NOTES: :[[@LINE-21]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + +// CHECK-NOTES: :[[@LINE-18]]:17: warning: function 'Z' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] +// CHECK-NOTES: :[[@LINE-15]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + }; +} + +void unittest_b2_08_01() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b2_08_01' has cognitive complexity of 8 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + struct X { + X() { +// CHECK-NOTES: :[[@LINE-1]]:5: note: nesting level increased to 1{{$}} + CC100; + + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } + + ~X() { +// CHECK-NOTES: :[[@LINE-1]]:5: note: nesting level increased to 1{{$}} + CC100; + + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } + + void Y() { +// CHECK-NOTES: :[[@LINE-1]]:5: note: nesting level increased to 1{{$}} + CC100; + + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } + + static void Z() { +// CHECK-NOTES: :[[@LINE-1]]:5: note: nesting level increased to 1{{$}} + CC100; + + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } + +// CHECK-NOTES: :[[@LINE-36]]:5: warning: function 'X' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] +// CHECK-NOTES: :[[@LINE-33]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + +// CHECK-NOTES: :[[@LINE-30]]:5: warning: function '~X' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] +// CHECK-NOTES: :[[@LINE-27]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + +// CHECK-NOTES: :[[@LINE-24]]:10: warning: function 'Y' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] +// CHECK-NOTES: :[[@LINE-21]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + +// CHECK-NOTES: :[[@LINE-18]]:17: warning: function 'Z' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] +// CHECK-NOTES: :[[@LINE-15]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + }; +} + +void unittest_b2_08_02() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b2_08_02' has cognitive complexity of 2 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + auto fun = []() { +// CHECK-NOTES: :[[@LINE-1]]:14: note: nesting level increased to 1{{$}} + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + }; +} + +//----------------------------------------------------------------------------// +//-------------------------- B2. Nesting increments --------------------------// +//----------------------------------------------------------------------------// +// Check that every thing listed in B3 of the specification does indeed // +// recieve the penalty of the current nesting level // +//----------------------------------------------------------------------------// + +void unittest_b3_00() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b3_00' has cognitive complexity of 3 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } +} + +void unittest_b3_01() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b3_01' has cognitive complexity of 3 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + int i = 1 ? 1 : 0; +// CHECK-NOTES: :[[@LINE-1]]:15: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} +// FIXME: would be nice to point at the '?' symbol. does not seem to be possible + } +} + +void unittest_b3_02(int x) { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b3_02' has cognitive complexity of 3 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + switch (x) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + case -1: + return; + default: + return; + } + } +} + +void unittest_b3_03() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b3_03' has cognitive complexity of 3 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + for (;;) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } +} + +void unittest_b3_04() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b3_04' has cognitive complexity of 3 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + SomeClass C; + for (int i : C) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } +} + +void unittest_b3_05() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b3_05' has cognitive complexity of 3 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + while (true) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } +} + +void unittest_b3_06() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b3_06' has cognitive complexity of 3 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + do { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } while (true); + } +} + +void unittest_b3_07() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b3_07' has cognitive complexity of 3 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + if (true) { +// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}} + } + } +} + +//----------------------------------------------------------------------------// +// Check that functions are being checked // +//----------------------------------------------------------------------------// + +class CheckClass { + CheckClass(int x) { +// CHECK-NOTES: :[[@LINE-1]]:3: warning: function 'CheckClass' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } + } + + void PrivateMemberFunction() { +// CHECK-NOTES: :[[@LINE-1]]:8: warning: function 'PrivateMemberFunction' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } + } + + void PrivateConstMemberFunction() const { +// CHECK-NOTES: :[[@LINE-1]]:8: warning: function 'PrivateConstMemberFunction' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } + } + + static void PrivateStaticMemberFunction() { +// CHECK-NOTES: :[[@LINE-1]]:15: warning: function 'PrivateStaticMemberFunction' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } + } + +public: + CheckClass() { +// CHECK-NOTES: :[[@LINE-1]]:3: warning: function 'CheckClass' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } + } + + ~CheckClass() { +// CHECK-NOTES: :[[@LINE-1]]:3: warning: function '~CheckClass' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } + } + + void PublicMemberFunction() { +// CHECK-NOTES: :[[@LINE-1]]:8: warning: function 'PublicMemberFunction' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } + } + + void PublicConstMemberFunction() const { +// CHECK-NOTES: :[[@LINE-1]]:8: warning: function 'PublicConstMemberFunction' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } + } + + static void PublicStaticMemberFunction() { +// CHECK-NOTES: :[[@LINE-1]]:15: warning: function 'PublicStaticMemberFunction' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } + } + + void PublicFunctionDefinition(); + +protected: + CheckClass(bool b) { +// CHECK-NOTES: :[[@LINE-1]]:3: warning: function 'CheckClass' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } + } + + void ProtectedMemberFunction() { +// CHECK-NOTES: :[[@LINE-1]]:8: warning: function 'ProtectedMemberFunction' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } + } + + void ProtectedConstMemberFunction() const { +// CHECK-NOTES: :[[@LINE-1]]:8: warning: function 'ProtectedConstMemberFunction' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } + } + + static void ProtectedStaticMemberFunction() { +// CHECK-NOTES: :[[@LINE-1]]:15: warning: function 'ProtectedStaticMemberFunction' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:7: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } + } +}; + +void CheckClass::PublicFunctionDefinition() { +// CHECK-NOTES: :[[@LINE-1]]:18: warning: function 'PublicFunctionDefinition' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } +} + +#define uglyfunctionmacro(name) \ + void name() { \ + CC100; \ + \ + if (true) { \ + try { \ + } catch (...) { \ + } \ + } \ + } + +uglyfunctionmacro(MacroFunction) +// CHECK-NOTES: :[[@LINE-1]]:19: warning: function 'MacroFunction' has cognitive complexity of 3 (threshold 0) [readability-function-cognitive-complexity] +// CHECK-NOTES: :[[@LINE-2]]:1: note: +1, including nesting penalty of 0, nesting level increased to 1 +// CHECK-NOTES: :[[@LINE-10]]:5: note: expanded from macro 'uglyfunctionmacro' +// CHECK-NOTES: :[[@LINE-4]]:1: note: +2, including nesting penalty of 1, nesting level increased to 2 +// CHECK-NOTES: :[[@LINE-10]]:9: note: expanded from macro 'uglyfunctionmacro' + +template +void templatedFunction() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'templatedFunction' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } +} + +template<> +void templatedFunction() { +// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'templatedFunction' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity] + CC100; + + try { + } catch (...) { +// CHECK-NOTES: :[[@LINE-1]]:5: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}} + } +} + +template void templatedFunction(); + +void functionThatCallsTemplatedFunctions() { + templatedFunction(); + + templatedFunction(); + + templatedFunction(); + + templatedFunction(); +}