84 lines · cpp
1//===- unittest/Format/FormatReplacementTest.cpp - Formatting unit test ---===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include "../Tooling/ReplacementTest.h"10#include "clang/Format/Format.h"11 12namespace clang {13namespace tooling {14namespace {15 16using format::FormatStyle;17using format::getLLVMStyle;18 19TEST_F(ReplacementTest, FormatCodeAfterReplacements) {20 // Column limit is 20.21 std::string Code = "Type *a =\n"22 " new Type();\n"23 "g(iiiii, 0, jjjjj,\n"24 " 0, kkkkk, 0, mm);\n"25 "int bad = format ;";26 std::string Expected = "auto a = new Type();\n"27 "g(iiiii, nullptr,\n"28 " jjjjj, nullptr,\n"29 " kkkkk, nullptr,\n"30 " mm);\n"31 "int bad = format ;";32 FileID ID = Context.createInMemoryFile("format.cpp", Code);33 tooling::Replacements Replaces = toReplacements(34 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,35 "auto "),36 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,37 "nullptr"),38 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,39 "nullptr"),40 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,41 "nullptr")});42 43 FormatStyle Style = getLLVMStyle();44 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.45 auto FormattedReplaces = formatReplacements(Code, Replaces, Style);46 EXPECT_TRUE(static_cast<bool>(FormattedReplaces))47 << llvm::toString(FormattedReplaces.takeError()) << "\n";48 auto Result = applyAllReplacements(Code, *FormattedReplaces);49 EXPECT_TRUE(static_cast<bool>(Result));50 EXPECT_EQ(Expected, *Result);51}52 53TEST_F(ReplacementTest, SortIncludesAfterReplacement) {54 std::string Code = "#include \"a.h\"\n"55 "#include \"c.h\"\n"56 "\n"57 "int main() {\n"58 " return 0;\n"59 "}";60 std::string Expected = "#include \"a.h\"\n"61 "#include \"b.h\"\n"62 "#include \"c.h\"\n"63 "\n"64 "int main() {\n"65 " return 0;\n"66 "}";67 FileID ID = Context.createInMemoryFile("fix.cpp", Code);68 tooling::Replacements Replaces = toReplacements(69 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,70 "#include \"b.h\"\n")});71 72 FormatStyle Style = getLLVMStyle();73 auto FormattedReplaces = formatReplacements(Code, Replaces, Style);74 EXPECT_TRUE(static_cast<bool>(FormattedReplaces))75 << llvm::toString(FormattedReplaces.takeError()) << "\n";76 auto Result = applyAllReplacements(Code, *FormattedReplaces);77 EXPECT_TRUE(static_cast<bool>(Result));78 EXPECT_EQ(Expected, *Result);79}80 81} // namespace82} // namespace tooling83} // namespace clang84