Can clang format add braces to single line if statements etc
clang-tidy can make syntactic changes to your code using FIXITS
clang-tidy YOUR_FILE.cpp -fix -checks="readability-braces-around-statements" -- COMPILE_OPTIONS
Updated:
clang-tidy is a bit of a heavyweight tool for this as it needs compile options to parse the file, sadly clang-format (as of v3.9) won't add braces.
COMPILE_OPTIONS
would be the include paths etc that you use to compile the file with, ie -std=c++14 -stdlib=libc++ -O2 -I.
If you have a compile_options.json
file from CMake then you can pass the path of the directory it is contained in to clang-tidy and it will look up the appropriate compile options for the file:
clang-tidy YOUR_FILE.cpp -fix -checks="readability-braces-around-statements" -p COMPILE_OPTIONS_DIR
Starting clang-format-15 (currently trunk), the answer is yes - using the new InsertBraces
option, which landed just today:
https://github.com/llvm/llvm-project/commit/77e60bc42c48e16d646488d43210b1630cd4db49
https://reviews.llvm.org/D120217
From the clang-format documentation:
InsertBraces (Boolean) clang-format 15
Insert braces after control statements (if, else, for, do, and while) in C++ unless the control statements are inside macro definitions or the braces would enclose preprocessor directives.
Warning:
Setting this option to true could lead to incorrect code formatting due to clang-format’s lack of complete semantic information. As such, extra care should be taken to review code changes made by this option.
false: true:
if (isa<FunctionDecl>(D)) vs. if (isa<FunctionDecl>(D)) {
handleFunctionDecl(D); handleFunctionDecl(D);
else if (isa<VarDecl>(D)) } else if (isa<VarDecl>(D)) {
handleVarDecl(D); handleVarDecl(D);
else } else {
return; return;
}
while (i--) vs. while (i--) {
for (auto *A : D.attrs()) for (auto *A : D.attrs()) {
handleAttr(A); handleAttr(A);
}
}
do vs. do {
--i; --i;
while (i); } while (i);