clang-tools 23.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
15void TrivialSwitchCheck::registerMatchers(MatchFinder *Finder) {
16 Finder->addMatcher(switchStmt().bind("switch"), this);
17}
18
19void TrivialSwitchCheck::check(const MatchFinder::MatchResult &Result) {
20 const auto *Switch = Result.Nodes.getNodeAs<SwitchStmt>("switch");
21 std::size_t CaseCount = 0;
22 bool HasDefault = false;
23
24 for (const SwitchCase *CurrentCase = Switch->getSwitchCaseList(); CurrentCase;
25 CurrentCase = CurrentCase->getNextSwitchCase()) {
26 ++CaseCount;
27 if (isa<DefaultStmt>(CurrentCase))
28 HasDefault = true;
29 }
30
31 // FIXME: Try to add fix-it for each case.
32 switch (const SourceLocation Loc = Switch->getBeginLoc(); CaseCount) {
33 case 0:
34 diag(Loc, "switch statement without labels has no effect");
35 return;
36 case 1:
37 if (HasDefault)
38 diag(Loc, "switch with default label only");
39 else
40 diag(Loc, "switch with only one case; use an if statement");
41 return;
42 case 2:
43 if (HasDefault)
44 diag(Loc, "switch could be better written as an if-else statement");
45 [[fallthrough]];
46 default:
47 break;
48 }
49}
50
51} // namespace clang::tidy::readability
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override