[clang] 3ecf872 - [clang-format] Detect language for file templates (#191502)
via cfe-commits
cfe-commits at lists.llvm.org
Tue Apr 14 23:26:19 PDT 2026
Author: Björn Schäpers
Date: 2026-04-15T08:26:14+02:00
New Revision: 3ecf8724de1744f92e311115d4f3834a49a15b7b
URL: https://github.com/llvm/llvm-project/commit/3ecf8724de1744f92e311115d4f3834a49a15b7b
DIFF: https://github.com/llvm/llvm-project/commit/3ecf8724de1744f92e311115d4f3834a49a15b7b.diff
LOG: [clang-format] Detect language for file templates (#191502)
Fixes #191295.
Added:
Modified:
clang/lib/Format/Format.cpp
clang/unittests/Format/FormatTest.cpp
Removed:
################################################################################
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 42190604b3881..48e139ea9d058 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -4427,7 +4427,15 @@ const char *StyleOptionHelpDescription =
"4. \"{key: value, ...}\" to set specific parameters, e.g.:\n"
" --style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
-static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
+static FormatStyle::LanguageKind getLanguageByFileName(StringRef &FileName) {
+ static constexpr std::array<llvm::StringLiteral, 2> TemplateSuffixes{
+ ".in",
+ ".template",
+ };
+ for (auto Suffix : TemplateSuffixes)
+ if (FileName.consume_back(Suffix))
+ break;
+
if (FileName.ends_with(".c"))
return FormatStyle::LK_C;
if (FileName.ends_with(".java"))
diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index abe546542b4af..457695cc09dcc 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -22354,6 +22354,7 @@ TEST_F(FormatTest, StructuredBindings) {
TEST_F(FormatTest, FileAndCode) {
EXPECT_EQ(FormatStyle::LK_C, guessLanguage("foo.c", ""));
+ EXPECT_EQ(FormatStyle::LK_C, guessLanguage("foo.c.in", ""));
EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
@@ -22523,6 +22524,9 @@ TEST_F(FormatTest, GetLanguageByComment) {
EXPECT_EQ(FormatStyle::LK_C,
guessLanguage("foo.h", "// clang-format Language: C\n"
"int i;"));
+ EXPECT_EQ(FormatStyle::LK_C,
+ guessLanguage("foo.h.in", "// clang-format Language: C\n"
+ "int i;"));
EXPECT_EQ(FormatStyle::LK_Cpp,
guessLanguage("foo.h", "// clang-format Language: Cpp\n"
"int DoStuff(CGRect rect);"));
More information about the cfe-commits
mailing list