ClangFormat.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. //===-- clang-format/ClangFormat.cpp - Clang format tool ------------------===//
  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-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. ///
  9. /// \file
  10. /// This file implements a clang-format tool that automatically formats
  11. /// (fragments of) C++ code.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Basic/Diagnostic.h"
  15. #include "clang/Basic/DiagnosticOptions.h"
  16. #include "clang/Basic/FileManager.h"
  17. #include "clang/Basic/SourceManager.h"
  18. #include "clang/Basic/Version.h"
  19. #include "clang/Format/Format.h"
  20. #include "clang/Rewrite/Core/Rewriter.h"
  21. #include "llvm/ADT/StringSwitch.h"
  22. #include "llvm/Support/CommandLine.h"
  23. #include "llvm/Support/FileSystem.h"
  24. #include "llvm/Support/InitLLVM.h"
  25. #include "llvm/Support/Process.h"
  26. #include <fstream>
  27. using namespace llvm;
  28. using clang::tooling::Replacements;
  29. static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
  30. // Mark all our options with this category, everything else (except for -version
  31. // and -help) will be hidden.
  32. static cl::OptionCategory ClangFormatCategory("Clang-format options");
  33. static cl::list<unsigned>
  34. Offsets("offset",
  35. cl::desc("Format a range starting at this byte offset.\n"
  36. "Multiple ranges can be formatted by specifying\n"
  37. "several -offset and -length pairs.\n"
  38. "Can only be used with one input file."),
  39. cl::cat(ClangFormatCategory));
  40. static cl::list<unsigned>
  41. Lengths("length",
  42. cl::desc("Format a range of this length (in bytes).\n"
  43. "Multiple ranges can be formatted by specifying\n"
  44. "several -offset and -length pairs.\n"
  45. "When only a single -offset is specified without\n"
  46. "-length, clang-format will format up to the end\n"
  47. "of the file.\n"
  48. "Can only be used with one input file."),
  49. cl::cat(ClangFormatCategory));
  50. static cl::list<std::string>
  51. LineRanges("lines",
  52. cl::desc("<start line>:<end line> - format a range of\n"
  53. "lines (both 1-based).\n"
  54. "Multiple ranges can be formatted by specifying\n"
  55. "several -lines arguments.\n"
  56. "Can't be used with -offset and -length.\n"
  57. "Can only be used with one input file."),
  58. cl::cat(ClangFormatCategory));
  59. static cl::opt<std::string>
  60. Style("style", cl::desc(clang::format::StyleOptionHelpDescription),
  61. cl::init(clang::format::DefaultFormatStyle),
  62. cl::cat(ClangFormatCategory));
  63. static cl::opt<std::string>
  64. FallbackStyle("fallback-style",
  65. cl::desc("The name of the predefined style used as a\n"
  66. "fallback in case clang-format is invoked with\n"
  67. "-style=file, but can not find the .clang-format\n"
  68. "file to use. Defaults to 'LLVM'.\n"
  69. "Use -fallback-style=none to skip formatting."),
  70. cl::init(clang::format::DefaultFallbackStyle),
  71. cl::cat(ClangFormatCategory));
  72. static cl::opt<std::string> AssumeFileName(
  73. "assume-filename",
  74. cl::desc("Set filename used to determine the language and to find\n"
  75. ".clang-format file.\n"
  76. "Only used when reading from stdin.\n"
  77. "If this is not passed, the .clang-format file is searched\n"
  78. "relative to the current working directory when reading stdin.\n"
  79. "Unrecognized filenames are treated as C++.\n"
  80. "supported:\n"
  81. " CSharp: .cs\n"
  82. " Java: .java\n"
  83. " JavaScript: .mjs .js .ts\n"
  84. " Json: .json\n"
  85. " Objective-C: .m .mm\n"
  86. " Proto: .proto .protodevel\n"
  87. " TableGen: .td\n"
  88. " TextProto: .textpb .pb.txt .textproto .asciipb\n"
  89. " Verilog: .sv .svh .v .vh"),
  90. cl::init("<stdin>"), cl::cat(ClangFormatCategory));
  91. static cl::opt<bool> Inplace("i",
  92. cl::desc("Inplace edit <file>s, if specified."),
  93. cl::cat(ClangFormatCategory));
  94. static cl::opt<bool> OutputXML("output-replacements-xml",
  95. cl::desc("Output replacements as XML."),
  96. cl::cat(ClangFormatCategory));
  97. static cl::opt<bool>
  98. DumpConfig("dump-config",
  99. cl::desc("Dump configuration options to stdout and exit.\n"
  100. "Can be used with -style option."),
  101. cl::cat(ClangFormatCategory));
  102. static cl::opt<unsigned>
  103. Cursor("cursor",
  104. cl::desc("The position of the cursor when invoking\n"
  105. "clang-format from an editor integration"),
  106. cl::init(0), cl::cat(ClangFormatCategory));
  107. static cl::opt<bool>
  108. SortIncludes("sort-includes",
  109. cl::desc("If set, overrides the include sorting behavior\n"
  110. "determined by the SortIncludes style flag"),
  111. cl::cat(ClangFormatCategory));
  112. static cl::opt<std::string> QualifierAlignment(
  113. "qualifier-alignment",
  114. cl::desc("If set, overrides the qualifier alignment style\n"
  115. "determined by the QualifierAlignment style flag"),
  116. cl::init(""), cl::cat(ClangFormatCategory));
  117. static cl::opt<std::string> Files(
  118. "files",
  119. cl::desc("A file containing a list of files to process, one per line."),
  120. cl::value_desc("filename"), cl::init(""), cl::cat(ClangFormatCategory));
  121. static cl::opt<bool>
  122. Verbose("verbose", cl::desc("If set, shows the list of processed files"),
  123. cl::cat(ClangFormatCategory));
  124. // Use --dry-run to match other LLVM tools when you mean do it but don't
  125. // actually do it
  126. static cl::opt<bool>
  127. DryRun("dry-run",
  128. cl::desc("If set, do not actually make the formatting changes"),
  129. cl::cat(ClangFormatCategory));
  130. // Use -n as a common command as an alias for --dry-run. (git and make use -n)
  131. static cl::alias DryRunShort("n", cl::desc("Alias for --dry-run"),
  132. cl::cat(ClangFormatCategory), cl::aliasopt(DryRun),
  133. cl::NotHidden);
  134. // Emulate being able to turn on/off the warning.
  135. static cl::opt<bool>
  136. WarnFormat("Wclang-format-violations",
  137. cl::desc("Warnings about individual formatting changes needed. "
  138. "Used only with --dry-run or -n"),
  139. cl::init(true), cl::cat(ClangFormatCategory), cl::Hidden);
  140. static cl::opt<bool>
  141. NoWarnFormat("Wno-clang-format-violations",
  142. cl::desc("Do not warn about individual formatting changes "
  143. "needed. Used only with --dry-run or -n"),
  144. cl::init(false), cl::cat(ClangFormatCategory), cl::Hidden);
  145. static cl::opt<unsigned> ErrorLimit(
  146. "ferror-limit",
  147. cl::desc("Set the maximum number of clang-format errors to emit\n"
  148. "before stopping (0 = no limit).\n"
  149. "Used only with --dry-run or -n"),
  150. cl::init(0), cl::cat(ClangFormatCategory));
  151. static cl::opt<bool>
  152. WarningsAsErrors("Werror",
  153. cl::desc("If set, changes formatting warnings to errors"),
  154. cl::cat(ClangFormatCategory));
  155. namespace {
  156. enum class WNoError { Unknown };
  157. }
  158. static cl::bits<WNoError> WNoErrorList(
  159. "Wno-error",
  160. cl::desc("If set don't error out on the specified warning type."),
  161. cl::values(
  162. clEnumValN(WNoError::Unknown, "unknown",
  163. "If set, unknown format options are only warned about.\n"
  164. "This can be used to enable formatting, even if the\n"
  165. "configuration contains unknown (newer) options.\n"
  166. "Use with caution, as this might lead to dramatically\n"
  167. "differing format depending on an option being\n"
  168. "supported or not.")),
  169. cl::cat(ClangFormatCategory));
  170. static cl::opt<bool>
  171. ShowColors("fcolor-diagnostics",
  172. cl::desc("If set, and on a color-capable terminal controls "
  173. "whether or not to print diagnostics in color"),
  174. cl::init(true), cl::cat(ClangFormatCategory), cl::Hidden);
  175. static cl::opt<bool>
  176. NoShowColors("fno-color-diagnostics",
  177. cl::desc("If set, and on a color-capable terminal controls "
  178. "whether or not to print diagnostics in color"),
  179. cl::init(false), cl::cat(ClangFormatCategory), cl::Hidden);
  180. static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
  181. cl::cat(ClangFormatCategory));
  182. namespace clang {
  183. namespace format {
  184. static FileID createInMemoryFile(StringRef FileName, MemoryBufferRef Source,
  185. SourceManager &Sources, FileManager &Files,
  186. llvm::vfs::InMemoryFileSystem *MemFS) {
  187. MemFS->addFileNoOwn(FileName, 0, Source);
  188. auto File = Files.getOptionalFileRef(FileName);
  189. assert(File && "File not added to MemFS?");
  190. return Sources.createFileID(*File, SourceLocation(), SrcMgr::C_User);
  191. }
  192. // Parses <start line>:<end line> input to a pair of line numbers.
  193. // Returns true on error.
  194. static bool parseLineRange(StringRef Input, unsigned &FromLine,
  195. unsigned &ToLine) {
  196. std::pair<StringRef, StringRef> LineRange = Input.split(':');
  197. return LineRange.first.getAsInteger(0, FromLine) ||
  198. LineRange.second.getAsInteger(0, ToLine);
  199. }
  200. static bool fillRanges(MemoryBuffer *Code,
  201. std::vector<tooling::Range> &Ranges) {
  202. IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
  203. new llvm::vfs::InMemoryFileSystem);
  204. FileManager Files(FileSystemOptions(), InMemoryFileSystem);
  205. DiagnosticsEngine Diagnostics(
  206. IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
  207. new DiagnosticOptions);
  208. SourceManager Sources(Diagnostics, Files);
  209. FileID ID = createInMemoryFile("<irrelevant>", *Code, Sources, Files,
  210. InMemoryFileSystem.get());
  211. if (!LineRanges.empty()) {
  212. if (!Offsets.empty() || !Lengths.empty()) {
  213. errs() << "error: cannot use -lines with -offset/-length\n";
  214. return true;
  215. }
  216. for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
  217. unsigned FromLine, ToLine;
  218. if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
  219. errs() << "error: invalid <start line>:<end line> pair\n";
  220. return true;
  221. }
  222. if (FromLine < 1) {
  223. errs() << "error: start line should be at least 1\n";
  224. return true;
  225. }
  226. if (FromLine > ToLine) {
  227. errs() << "error: start line should not exceed end line\n";
  228. return true;
  229. }
  230. SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
  231. SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
  232. if (Start.isInvalid() || End.isInvalid())
  233. return true;
  234. unsigned Offset = Sources.getFileOffset(Start);
  235. unsigned Length = Sources.getFileOffset(End) - Offset;
  236. Ranges.push_back(tooling::Range(Offset, Length));
  237. }
  238. return false;
  239. }
  240. if (Offsets.empty())
  241. Offsets.push_back(0);
  242. if (Offsets.size() != Lengths.size() &&
  243. !(Offsets.size() == 1 && Lengths.empty())) {
  244. errs() << "error: number of -offset and -length arguments must match.\n";
  245. return true;
  246. }
  247. for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
  248. if (Offsets[i] >= Code->getBufferSize()) {
  249. errs() << "error: offset " << Offsets[i] << " is outside the file\n";
  250. return true;
  251. }
  252. SourceLocation Start =
  253. Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
  254. SourceLocation End;
  255. if (i < Lengths.size()) {
  256. if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
  257. errs() << "error: invalid length " << Lengths[i]
  258. << ", offset + length (" << Offsets[i] + Lengths[i]
  259. << ") is outside the file.\n";
  260. return true;
  261. }
  262. End = Start.getLocWithOffset(Lengths[i]);
  263. } else {
  264. End = Sources.getLocForEndOfFile(ID);
  265. }
  266. unsigned Offset = Sources.getFileOffset(Start);
  267. unsigned Length = Sources.getFileOffset(End) - Offset;
  268. Ranges.push_back(tooling::Range(Offset, Length));
  269. }
  270. return false;
  271. }
  272. static void outputReplacementXML(StringRef Text) {
  273. // FIXME: When we sort includes, we need to make sure the stream is correct
  274. // utf-8.
  275. size_t From = 0;
  276. size_t Index;
  277. while ((Index = Text.find_first_of("\n\r<&", From)) != StringRef::npos) {
  278. outs() << Text.substr(From, Index - From);
  279. switch (Text[Index]) {
  280. case '\n':
  281. outs() << "&#10;";
  282. break;
  283. case '\r':
  284. outs() << "&#13;";
  285. break;
  286. case '<':
  287. outs() << "&lt;";
  288. break;
  289. case '&':
  290. outs() << "&amp;";
  291. break;
  292. default:
  293. llvm_unreachable("Unexpected character encountered!");
  294. }
  295. From = Index + 1;
  296. }
  297. outs() << Text.substr(From);
  298. }
  299. static void outputReplacementsXML(const Replacements &Replaces) {
  300. for (const auto &R : Replaces) {
  301. outs() << "<replacement "
  302. << "offset='" << R.getOffset() << "' "
  303. << "length='" << R.getLength() << "'>";
  304. outputReplacementXML(R.getReplacementText());
  305. outs() << "</replacement>\n";
  306. }
  307. }
  308. static bool
  309. emitReplacementWarnings(const Replacements &Replaces, StringRef AssumedFileName,
  310. const std::unique_ptr<llvm::MemoryBuffer> &Code) {
  311. if (Replaces.empty())
  312. return false;
  313. unsigned Errors = 0;
  314. if (WarnFormat && !NoWarnFormat) {
  315. llvm::SourceMgr Mgr;
  316. const char *StartBuf = Code->getBufferStart();
  317. Mgr.AddNewSourceBuffer(
  318. MemoryBuffer::getMemBuffer(StartBuf, AssumedFileName), SMLoc());
  319. for (const auto &R : Replaces) {
  320. SMDiagnostic Diag = Mgr.GetMessage(
  321. SMLoc::getFromPointer(StartBuf + R.getOffset()),
  322. WarningsAsErrors ? SourceMgr::DiagKind::DK_Error
  323. : SourceMgr::DiagKind::DK_Warning,
  324. "code should be clang-formatted [-Wclang-format-violations]");
  325. Diag.print(nullptr, llvm::errs(), (ShowColors && !NoShowColors));
  326. if (ErrorLimit && ++Errors >= ErrorLimit)
  327. break;
  328. }
  329. }
  330. return WarningsAsErrors;
  331. }
  332. static void outputXML(const Replacements &Replaces,
  333. const Replacements &FormatChanges,
  334. const FormattingAttemptStatus &Status,
  335. const cl::opt<unsigned> &Cursor,
  336. unsigned CursorPosition) {
  337. outs() << "<?xml version='1.0'?>\n<replacements "
  338. "xml:space='preserve' incomplete_format='"
  339. << (Status.FormatComplete ? "false" : "true") << "'";
  340. if (!Status.FormatComplete)
  341. outs() << " line='" << Status.Line << "'";
  342. outs() << ">\n";
  343. if (Cursor.getNumOccurrences() != 0) {
  344. outs() << "<cursor>" << FormatChanges.getShiftedCodePosition(CursorPosition)
  345. << "</cursor>\n";
  346. }
  347. outputReplacementsXML(Replaces);
  348. outs() << "</replacements>\n";
  349. }
  350. class ClangFormatDiagConsumer : public DiagnosticConsumer {
  351. virtual void anchor() {}
  352. void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
  353. const Diagnostic &Info) override {
  354. SmallVector<char, 16> vec;
  355. Info.FormatDiagnostic(vec);
  356. errs() << "clang-format error:" << vec << "\n";
  357. }
  358. };
  359. // Returns true on error.
  360. static bool format(StringRef FileName) {
  361. if (!OutputXML && Inplace && FileName == "-") {
  362. errs() << "error: cannot use -i when reading from stdin.\n";
  363. return false;
  364. }
  365. // On Windows, overwriting a file with an open file mapping doesn't work,
  366. // so read the whole file into memory when formatting in-place.
  367. ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
  368. !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName)
  369. : MemoryBuffer::getFileOrSTDIN(FileName);
  370. if (std::error_code EC = CodeOrErr.getError()) {
  371. errs() << EC.message() << "\n";
  372. return true;
  373. }
  374. std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
  375. if (Code->getBufferSize() == 0)
  376. return false; // Empty files are formatted correctly.
  377. StringRef BufStr = Code->getBuffer();
  378. const char *InvalidBOM = SrcMgr::ContentCache::getInvalidBOM(BufStr);
  379. if (InvalidBOM) {
  380. errs() << "error: encoding with unsupported byte order mark \""
  381. << InvalidBOM << "\" detected";
  382. if (FileName != "-")
  383. errs() << " in file '" << FileName << "'";
  384. errs() << ".\n";
  385. return true;
  386. }
  387. std::vector<tooling::Range> Ranges;
  388. if (fillRanges(Code.get(), Ranges))
  389. return true;
  390. StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName;
  391. if (AssumedFileName.empty()) {
  392. llvm::errs() << "error: empty filenames are not allowed\n";
  393. return true;
  394. }
  395. llvm::Expected<FormatStyle> FormatStyle =
  396. getStyle(Style, AssumedFileName, FallbackStyle, Code->getBuffer(),
  397. nullptr, WNoErrorList.isSet(WNoError::Unknown));
  398. if (!FormatStyle) {
  399. llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
  400. return true;
  401. }
  402. StringRef QualifierAlignmentOrder = QualifierAlignment;
  403. FormatStyle->QualifierAlignment =
  404. StringSwitch<FormatStyle::QualifierAlignmentStyle>(
  405. QualifierAlignmentOrder.lower())
  406. .Case("right", FormatStyle::QAS_Right)
  407. .Case("left", FormatStyle::QAS_Left)
  408. .Default(FormatStyle->QualifierAlignment);
  409. if (FormatStyle->QualifierAlignment == FormatStyle::QAS_Left) {
  410. FormatStyle->QualifierOrder = {"const", "volatile", "type"};
  411. } else if (FormatStyle->QualifierAlignment == FormatStyle::QAS_Right) {
  412. FormatStyle->QualifierOrder = {"type", "const", "volatile"};
  413. } else if (QualifierAlignmentOrder.contains("type")) {
  414. FormatStyle->QualifierAlignment = FormatStyle::QAS_Custom;
  415. SmallVector<StringRef> Qualifiers;
  416. QualifierAlignmentOrder.split(Qualifiers, " ", /*MaxSplit=*/-1,
  417. /*KeepEmpty=*/false);
  418. FormatStyle->QualifierOrder = {Qualifiers.begin(), Qualifiers.end()};
  419. }
  420. if (SortIncludes.getNumOccurrences() != 0) {
  421. if (SortIncludes)
  422. FormatStyle->SortIncludes = FormatStyle::SI_CaseSensitive;
  423. else
  424. FormatStyle->SortIncludes = FormatStyle::SI_Never;
  425. }
  426. unsigned CursorPosition = Cursor;
  427. Replacements Replaces = sortIncludes(*FormatStyle, Code->getBuffer(), Ranges,
  428. AssumedFileName, &CursorPosition);
  429. // To format JSON insert a variable to trick the code into thinking its
  430. // JavaScript.
  431. if (FormatStyle->isJson() && !FormatStyle->DisableFormat) {
  432. auto Err = Replaces.add(tooling::Replacement(
  433. tooling::Replacement(AssumedFileName, 0, 0, "x = ")));
  434. if (Err)
  435. llvm::errs() << "Bad Json variable insertion\n";
  436. }
  437. auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces);
  438. if (!ChangedCode) {
  439. llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
  440. return true;
  441. }
  442. // Get new affected ranges after sorting `#includes`.
  443. Ranges = tooling::calculateRangesAfterReplacements(Replaces, Ranges);
  444. FormattingAttemptStatus Status;
  445. Replacements FormatChanges =
  446. reformat(*FormatStyle, *ChangedCode, Ranges, AssumedFileName, &Status);
  447. Replaces = Replaces.merge(FormatChanges);
  448. if (OutputXML || DryRun) {
  449. if (DryRun)
  450. return emitReplacementWarnings(Replaces, AssumedFileName, Code);
  451. else
  452. outputXML(Replaces, FormatChanges, Status, Cursor, CursorPosition);
  453. } else {
  454. IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
  455. new llvm::vfs::InMemoryFileSystem);
  456. FileManager Files(FileSystemOptions(), InMemoryFileSystem);
  457. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions());
  458. ClangFormatDiagConsumer IgnoreDiagnostics;
  459. DiagnosticsEngine Diagnostics(
  460. IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), &*DiagOpts,
  461. &IgnoreDiagnostics, false);
  462. SourceManager Sources(Diagnostics, Files);
  463. FileID ID = createInMemoryFile(AssumedFileName, *Code, Sources, Files,
  464. InMemoryFileSystem.get());
  465. Rewriter Rewrite(Sources, LangOptions());
  466. tooling::applyAllReplacements(Replaces, Rewrite);
  467. if (Inplace) {
  468. if (Rewrite.overwriteChangedFiles())
  469. return true;
  470. } else {
  471. if (Cursor.getNumOccurrences() != 0) {
  472. outs() << "{ \"Cursor\": "
  473. << FormatChanges.getShiftedCodePosition(CursorPosition)
  474. << ", \"IncompleteFormat\": "
  475. << (Status.FormatComplete ? "false" : "true");
  476. if (!Status.FormatComplete)
  477. outs() << ", \"Line\": " << Status.Line;
  478. outs() << " }\n";
  479. }
  480. Rewrite.getEditBuffer(ID).write(outs());
  481. }
  482. }
  483. return false;
  484. }
  485. } // namespace format
  486. } // namespace clang
  487. static void PrintVersion(raw_ostream &OS) {
  488. OS << clang::getClangToolFullVersion("clang-format") << '\n';
  489. }
  490. // Dump the configuration.
  491. static int dumpConfig() {
  492. StringRef FileName;
  493. std::unique_ptr<llvm::MemoryBuffer> Code;
  494. if (FileNames.empty()) {
  495. // We can't read the code to detect the language if there's no
  496. // file name, so leave Code empty here.
  497. FileName = AssumeFileName;
  498. } else {
  499. // Read in the code in case the filename alone isn't enough to
  500. // detect the language.
  501. ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
  502. MemoryBuffer::getFileOrSTDIN(FileNames[0]);
  503. if (std::error_code EC = CodeOrErr.getError()) {
  504. llvm::errs() << EC.message() << "\n";
  505. return 1;
  506. }
  507. FileName = (FileNames[0] == "-") ? AssumeFileName : FileNames[0];
  508. Code = std::move(CodeOrErr.get());
  509. }
  510. llvm::Expected<clang::format::FormatStyle> FormatStyle =
  511. clang::format::getStyle(Style, FileName, FallbackStyle,
  512. Code ? Code->getBuffer() : "");
  513. if (!FormatStyle) {
  514. llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
  515. return 1;
  516. }
  517. std::string Config = clang::format::configurationAsText(*FormatStyle);
  518. outs() << Config << "\n";
  519. return 0;
  520. }
  521. int main(int argc, const char **argv) {
  522. llvm::InitLLVM X(argc, argv);
  523. cl::HideUnrelatedOptions(ClangFormatCategory);
  524. cl::SetVersionPrinter(PrintVersion);
  525. cl::ParseCommandLineOptions(
  526. argc, argv,
  527. "A tool to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# "
  528. "code.\n\n"
  529. "If no arguments are specified, it formats the code from standard input\n"
  530. "and writes the result to the standard output.\n"
  531. "If <file>s are given, it reformats the files. If -i is specified\n"
  532. "together with <file>s, the files are edited in-place. Otherwise, the\n"
  533. "result is written to the standard output.\n");
  534. if (Help) {
  535. cl::PrintHelpMessage();
  536. return 0;
  537. }
  538. if (DumpConfig)
  539. return dumpConfig();
  540. if (!Files.empty()) {
  541. std::ifstream ExternalFileOfFiles{std::string(Files)};
  542. std::string Line;
  543. unsigned LineNo = 1;
  544. while (std::getline(ExternalFileOfFiles, Line)) {
  545. FileNames.push_back(Line);
  546. LineNo++;
  547. }
  548. errs() << "Clang-formating " << LineNo << " files\n";
  549. }
  550. bool Error = false;
  551. if (FileNames.empty()) {
  552. Error = clang::format::format("-");
  553. return Error ? 1 : 0;
  554. }
  555. if (FileNames.size() != 1 &&
  556. (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty())) {
  557. errs() << "error: -offset, -length and -lines can only be used for "
  558. "single file.\n";
  559. return 1;
  560. }
  561. unsigned FileNo = 1;
  562. for (const auto &FileName : FileNames) {
  563. if (Verbose) {
  564. errs() << "Formatting [" << FileNo++ << "/" << FileNames.size() << "] "
  565. << FileName << "\n";
  566. }
  567. Error |= clang::format::format(FileName);
  568. }
  569. return Error ? 1 : 0;
  570. }