Skip to content

Commit 802f4f7

Browse files
owencatstellar
authored andcommitted
[clang-format] Handle raw string literals containing JSON code (llvm#140666)
Fix llvm#65400 (cherry picked from commit 0dfdf7e)
1 parent 9b08325 commit 802f4f7

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
@@ -3743,8 +3743,10 @@ reformat(const FormatStyle &Style, StringRef Code,
37433743
tooling::Replacements Replaces =
37443744
Formatter(*Env, Style, Status).process().first;
37453745
// add a replacement to remove the "x = " from the result.
3746-
Replaces = Replaces.merge(
3747-
tooling::Replacements(tooling::Replacement(FileName, 0, 4, "")));
3746+
if (Code.starts_with("x = ")) {
3747+
Replaces = Replaces.merge(
3748+
tooling::Replacements(tooling::Replacement(FileName, 0, 4, "")));
3749+
}
37483750
// apply the reformatting changes and the removal of "x = ".
37493751
if (applyAllReplacements(Code, Replaces))
37503752
return {Replaces, 0};

clang/tools/clang-format/ClangFormat.cpp

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

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)