• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- BracesAroundStatementsCheck.h - clang-tidy -------------*- C++ -*-===//
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 
9 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_BRACESAROUNDSTATEMENTSCHECK_H
10 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_BRACESAROUNDSTATEMENTSCHECK_H
11 
12 #include "../ClangTidyCheck.h"
13 
14 namespace clang {
15 namespace tidy {
16 namespace readability {
17 
18 /// Checks that bodies of `if` statements and loops (`for`, `range-for`,
19 /// `do-while`, and `while`) are inside braces
20 ///
21 /// Before:
22 ///
23 /// \code
24 ///   if (condition)
25 ///     statement;
26 /// \endcode
27 ///
28 /// After:
29 ///
30 /// \code
31 ///   if (condition) {
32 ///     statement;
33 ///   }
34 /// \endcode
35 ///
36 /// Additionally, one can define an option `ShortStatementLines` defining the
37 /// minimal number of lines that the statement should have in order to trigger
38 /// this check.
39 ///
40 /// The number of lines is counted from the end of condition or initial keyword
41 /// (`do`/`else`) until the last line of the inner statement.  Default value 0
42 /// means that braces will be added to all statements (not having them already).
43 class BracesAroundStatementsCheck : public ClangTidyCheck {
44 public:
45   BracesAroundStatementsCheck(StringRef Name, ClangTidyContext *Context);
46   void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
47   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
48   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
49   void onEndOfTranslationUnit() override;
50 
51 private:
52   bool checkStmt(const ast_matchers::MatchFinder::MatchResult &Result,
53                  const Stmt *S, SourceLocation StartLoc,
54                  SourceLocation EndLocHint = SourceLocation());
55   template <typename IfOrWhileStmt>
56   SourceLocation findRParenLoc(const IfOrWhileStmt *S, const SourceManager &SM,
57                                const ASTContext *Context);
58 
59 private:
60   std::set<const Stmt *> ForceBracesStmts;
61   const unsigned ShortStatementLines;
62 };
63 
64 } // namespace readability
65 } // namespace tidy
66 } // namespace clang
67 
68 #endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_BRACESAROUNDSTATEMENTSCHECK_H
69