Skip to content

Commit 0dfdf7e

Browse files
authored
[clang-format] Handle raw string literals containing JSON code (#140666)
Fix #65400
1 parent 701fe51 commit 0dfdf7e

File tree

3 files changed

+28
-4
lines changed

3 files changed

+28
-4
lines changed

clang/lib/Format/Format.cpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3808,8 +3808,10 @@ reformat(const FormatStyle &Style, StringRef Code,
38083808
tooling::Replacements Replaces =
38093809
Formatter(*Env, Style, Status).process().first;
38103810
// add a replacement to remove the "x = " from the result.
3811-
Replaces = Replaces.merge(
3812-
tooling::Replacements(tooling::Replacement(FileName, 0, 4, "")));
3811+
if (Code.starts_with("x = ")) {
3812+
Replaces = Replaces.merge(
3813+
tooling::Replacements(tooling::Replacement(FileName, 0, 4, "")));
3814+
}
38133815
// apply the reformatting changes and the removal of "x = ".
38143816
if (applyAllReplacements(Code, Replaces))
38153817
return {Replaces, 0};

clang/tools/clang-format/ClangFormat.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -491,8 +491,8 @@ static bool format(StringRef FileName, bool ErrorOnIncompleteFormat = false) {
491491
// To format JSON insert a variable to trick the code into thinking its
492492
// JavaScript.
493493
if (IsJson && !FormatStyle->DisableFormat) {
494-
auto Err = Replaces.add(tooling::Replacement(
495-
tooling::Replacement(AssumedFileName, 0, 0, "x = ")));
494+
auto Err =
495+
Replaces.add(tooling::Replacement(AssumedFileName, 0, 0, "x = "));
496496
if (Err)
497497
llvm::errs() << "Bad Json variable insertion\n";
498498
}

clang/unittests/Format/FormatTestRawStrings.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -988,6 +988,28 @@ fffffffffffffffffffff("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
988988
)pb");)test",
989989
Style));
990990
}
991+
992+
TEST_F(FormatTestRawStrings, Json) {
993+
auto Style = getLLVMStyle();
994+
Style.RawStringFormats = {
995+
{
996+
/*Language=*/FormatStyle::LK_Json,
997+
/*Delimiters=*/{"json"},
998+
/*EnclosingFunctions=*/{},
999+
/*CanonicalDelimiter=*/"",
1000+
/*BasedOnStyle=*/"llvm",
1001+
},
1002+
};
1003+
1004+
EXPECT_EQ("json = R\"json({\n"
1005+
" \"str\": \"test\"\n"
1006+
" })json\";",
1007+
format("json = R\"json({\n"
1008+
" \"str\": \"test\"\n"
1009+
"})json\";",
1010+
Style));
1011+
}
1012+
9911013
} // end namespace
9921014
} // end namespace format
9931015
} // end namespace clang

0 commit comments

Comments
 (0)