Skip to content

Commit 05fb840

Browse files
authored
[clang-format] Allow Language: Cpp for C files (llvm#133033)
Fix llvm#132832
1 parent b8a0558 commit 05fb840

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

clang/lib/Format/Format.cpp

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2123,10 +2123,14 @@ std::error_code parseConfiguration(llvm::MemoryBufferRef Config,
21232123
FormatStyle::FormatStyleSet StyleSet;
21242124
bool LanguageFound = false;
21252125
for (const FormatStyle &Style : llvm::reverse(Styles)) {
2126-
if (Style.Language != FormatStyle::LK_None)
2126+
const auto Lang = Style.Language;
2127+
if (Lang != FormatStyle::LK_None)
21272128
StyleSet.Add(Style);
2128-
if (Style.Language == Language)
2129+
if (Lang == Language ||
2130+
// For backward compatibility.
2131+
(Lang == FormatStyle::LK_Cpp && Language == FormatStyle::LK_C)) {
21292132
LanguageFound = true;
2133+
}
21302134
}
21312135
if (!LanguageFound) {
21322136
if (Styles.empty() || Styles[0].Language != FormatStyle::LK_None)
@@ -2166,8 +2170,14 @@ FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind Language) const {
21662170
if (!Styles)
21672171
return std::nullopt;
21682172
auto It = Styles->find(Language);
2169-
if (It == Styles->end())
2170-
return std::nullopt;
2173+
if (It == Styles->end()) {
2174+
if (Language != FormatStyle::LK_C)
2175+
return std::nullopt;
2176+
// For backward compatibility.
2177+
It = Styles->find(FormatStyle::LK_Cpp);
2178+
if (It == Styles->end())
2179+
return std::nullopt;
2180+
}
21712181
FormatStyle Style = It->second;
21722182
Style.StyleSet = *this;
21732183
return Style;

clang/unittests/Format/ConfigParseTest.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1230,6 +1230,26 @@ TEST(ConfigParseTest, ParsesConfigurationWithLanguages) {
12301230
IndentWidth, 56u);
12311231
}
12321232

1233+
TEST(ConfigParseTest, AllowCppForC) {
1234+
FormatStyle Style = {};
1235+
Style.Language = FormatStyle::LK_C;
1236+
EXPECT_EQ(parseConfiguration("Language: Cpp", &Style), ParseError::Success);
1237+
1238+
CHECK_PARSE("---\n"
1239+
"IndentWidth: 4\n"
1240+
"---\n"
1241+
"Language: Cpp\n"
1242+
"IndentWidth: 8\n",
1243+
IndentWidth, 8u);
1244+
1245+
EXPECT_EQ(parseConfiguration("---\n"
1246+
"Language: ObjC\n"
1247+
"---\n"
1248+
"Language: Cpp\n",
1249+
&Style),
1250+
ParseError::Success);
1251+
}
1252+
12331253
TEST(ConfigParseTest, UsesLanguageForBasedOnStyle) {
12341254
FormatStyle Style = {};
12351255
Style.Language = FormatStyle::LK_JavaScript;

0 commit comments

Comments
 (0)