Skip to content

release/20.x: [clang-format] Handle raw string literals containing JSON code (#140666) #141002

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

Open
wants to merge 1 commit into
base: release/20.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
6 changes: 4 additions & 2 deletions clang/lib/Format/Format.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3743,8 +3743,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 @@ -492,8 +492,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("json = R\"json({\n"
" \"str\": \"test\"\n"
" })json\";",
format("json = R\"json({\n"
" \"str\": \"test\"\n"
"})json\";",
Style));
}

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