Skip to content

[clang-format] Handle raw string literals containing JSON code #140666

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 21, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
[clang-format] Handle raw string literals containing JSON code
Fix #65400
  • Loading branch information
owenca committed May 20, 2025
commit 7c1c0d2ca413503d81cd71e6a005a608cdec479d
6 changes: 4 additions & 2 deletions clang/lib/Format/Format.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3808,8 +3808,10 @@ reformat(const FormatStyle &Style, StringRef Code,
tooling::Replacements Replaces =
Formatter(*Env, Style, Status).process().first;
// add a replacement to remove the "x = " from the result.
Replaces = Replaces.merge(
tooling::Replacements(tooling::Replacement(FileName, 0, 4, "")));
if (Code.starts_with("x = ")) {
Replaces = Replaces.merge(
tooling::Replacements(tooling::Replacement(FileName, 0, 4, "")));
}
// apply the reformatting changes and the removal of "x = ".
if (applyAllReplacements(Code, Replaces))
return {Replaces, 0};
Expand Down
4 changes: 2 additions & 2 deletions clang/tools/clang-format/ClangFormat.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -491,8 +491,8 @@ static bool format(StringRef FileName, bool ErrorOnIncompleteFormat = false) {
// To format JSON insert a variable to trick the code into thinking its
// JavaScript.
if (IsJson && !FormatStyle->DisableFormat) {
auto Err = Replaces.add(tooling::Replacement(
tooling::Replacement(AssumedFileName, 0, 0, "x = ")));
auto Err =
Replaces.add(tooling::Replacement(AssumedFileName, 0, 0, "x = "));
if (Err)
llvm::errs() << "Bad Json variable insertion\n";
}
Expand Down
22 changes: 22 additions & 0 deletions clang/unittests/Format/FormatTestRawStrings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -988,6 +988,28 @@ fffffffffffffffffffff("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
)pb");)test",
Style));
}

TEST_F(FormatTestRawStrings, Json) {
auto Style = getLLVMStyle();
Style.RawStringFormats = {
{
/*Language=*/FormatStyle::LK_Json,
/*Delimiters=*/{"json"},
/*EnclosingFunctions=*/{},
/*CanonicalDelimiter=*/"",
/*BasedOnStyle=*/"llvm",
},
};

EXPECT_EQ(R"test(json = R"json({
"str": "test"
})json";)test",
format(R"test(json = R"json({
"str": "test"
})json";)test",
Style));
}

} // end namespace
} // end namespace format
} // end namespace clang