[clang] [clang-format] Detect language for file templates (PR #191502)

Björn Schäpers via cfe-commits cfe-commits at lists.llvm.org
Fri Apr 10 12:53:33 PDT 2026


https://github.com/HazardyKnusperkeks updated https://github.com/llvm/llvm-project/pull/191502

>From b3975fd5066f7d4576f04542a26c75c7ca2fc30f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bj=C3=B6rn=20Sch=C3=A4pers?= <bjoern at hazardy.de>
Date: Fri, 10 Apr 2026 21:41:21 +0200
Subject: [PATCH] [clang-format] Detect language for file templates

Fixes #191295.
---
 clang/lib/Format/Format.cpp           | 8 +++++++-
 clang/unittests/Format/FormatTest.cpp | 4 ++++
 2 files changed, 11 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 42190604b3881..ecee57587f812 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -4427,7 +4427,13 @@ 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) {
+  constexpr std::array TemplateSuffixes{StringRef{".in"},
+                                        StringRef{".template"}};
+  for (auto Suffix : TemplateSuffixes)
+    if (FileName.ends_with(Suffix))
+      FileName = FileName.drop_back(Suffix.size());
+
   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