clang-tools 24.0.0git
TrivialSwitchCheck.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
10
11using namespace clang::ast_matchers;
12
14
16 ClangTidyContext *Context)
17 : ClangTidyCheck(Name, Context),
18 IgnoreMacros(Options.get("IgnoreMacros", true)) {}
19
21 Options.store(Opts, "IgnoreMacros", IgnoreMacros);
22}
23
24void TrivialSwitchCheck::registerMatchers(MatchFinder *Finder) {
25 Finder->addMatcher(switchStmt().bind("switch"), this);
26}
27
28void TrivialSwitchCheck::check(const MatchFinder::MatchResult &Result) {
29 const auto *Switch = Result.Nodes.getNodeAs<SwitchStmt>("switch");
30 if (IgnoreMacros && Switch->getBeginLoc().isMacroID())
31 return;
32
33 std::size_t CaseCount = 0;
34 bool HasDefault = false;
35
36 for (const SwitchCase *CurrentCase = Switch->getSwitchCaseList(); CurrentCase;
37 CurrentCase = CurrentCase->getNextSwitchCase()) {
38 ++CaseCount;
39 if (isa<DefaultStmt>(CurrentCase))
40 HasDefault = true;
41 }
42
43 // FIXME: Try to add fix-it for each case.
44 switch (const SourceLocation Loc = Switch->getBeginLoc(); CaseCount) {
45 case 0:
46 diag(Loc, "switch statement without labels has no effect");
47 return;
48 case 1:
49 if (HasDefault)
50 diag(Loc, "switch with default label only");
51 else
52 diag(Loc, "switch with only one case; use an if statement");
53 return;
54 case 2:
55 if (HasDefault)
56 diag(Loc, "switch could be better written as an if-else statement");
57 [[fallthrough]];
58 default:
59 break;
60 }
61}
62
63} // namespace clang::tidy::readability
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
TrivialSwitchCheck(StringRef Name, ClangTidyContext *Context)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
llvm::StringMap< ClangTidyValue > OptionMap