Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 1 | //===-- clang-format/ClangFormat.cpp - Clang format tool ------------------===// |
| 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 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 |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | /// |
| 9 | /// \file |
Adrian Prantl | 9fc8faf | 2018-05-09 01:00:01 +0000 | [diff] [blame] | 10 | /// This file implements a clang-format tool that automatically formats |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 11 | /// (fragments of) C++ code. |
| 12 | /// |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
| 15 | #include "clang/Basic/Diagnostic.h" |
| 16 | #include "clang/Basic/DiagnosticOptions.h" |
| 17 | #include "clang/Basic/FileManager.h" |
| 18 | #include "clang/Basic/SourceManager.h" |
Nico Weber | b00d66e | 2014-01-07 16:27:35 +0000 | [diff] [blame] | 19 | #include "clang/Basic/Version.h" |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 20 | #include "clang/Format/Format.h" |
Vlad Tsyrklevich | efed314 | 2019-10-29 10:20:38 -0700 | [diff] [blame] | 21 | #include "clang/Frontend/TextDiagnosticPrinter.h" |
Daniel Jasper | 867a938 | 2015-09-30 13:59:29 +0000 | [diff] [blame] | 22 | #include "clang/Rewrite/Core/Rewriter.h" |
Daniel Jasper | 06dbac4 | 2014-10-29 22:42:53 +0000 | [diff] [blame] | 23 | #include "llvm/Support/CommandLine.h" |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 24 | #include "llvm/Support/FileSystem.h" |
Rui Ueyama | e4b59a9 | 2018-04-13 20:57:57 +0000 | [diff] [blame] | 25 | #include "llvm/Support/InitLLVM.h" |
Alexander Kornienko | 54dcb53 | 2018-03-26 13:54:17 +0000 | [diff] [blame] | 26 | #include "llvm/Support/Process.h" |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 27 | |
| 28 | using namespace llvm; |
Daniel Jasper | d89ae9d | 2015-09-23 08:30:47 +0000 | [diff] [blame] | 29 | using clang::tooling::Replacements; |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 30 | |
| 31 | static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden); |
| 32 | |
Alexander Kornienko | 88a0d93 | 2013-05-10 18:12:00 +0000 | [diff] [blame] | 33 | // Mark all our options with this category, everything else (except for -version |
| 34 | // and -help) will be hidden. |
Alexander Kornienko | 3bb8fbf | 2014-02-05 13:42:43 +0000 | [diff] [blame] | 35 | static cl::OptionCategory ClangFormatCategory("Clang-format options"); |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 36 | |
Alexander Kornienko | 88a0d93 | 2013-05-10 18:12:00 +0000 | [diff] [blame] | 37 | static cl::list<unsigned> |
| 38 | Offsets("offset", |
| 39 | cl::desc("Format a range starting at this byte offset.\n" |
| 40 | "Multiple ranges can be formatted by specifying\n" |
| 41 | "several -offset and -length pairs.\n" |
| 42 | "Can only be used with one input file."), |
| 43 | cl::cat(ClangFormatCategory)); |
| 44 | static cl::list<unsigned> |
| 45 | Lengths("length", |
| 46 | cl::desc("Format a range of this length (in bytes).\n" |
| 47 | "Multiple ranges can be formatted by specifying\n" |
| 48 | "several -offset and -length pairs.\n" |
| 49 | "When only a single -offset is specified without\n" |
| 50 | "-length, clang-format will format up to the end\n" |
| 51 | "of the file.\n" |
| 52 | "Can only be used with one input file."), |
| 53 | cl::cat(ClangFormatCategory)); |
Alexander Kornienko | a49732f | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 54 | static cl::list<std::string> |
Paul Hoad | a65cfe3 | 2019-10-07 16:53:35 +0000 | [diff] [blame] | 55 | LineRanges("lines", |
| 56 | cl::desc("<start line>:<end line> - format a range of\n" |
| 57 | "lines (both 1-based).\n" |
| 58 | "Multiple ranges can be formatted by specifying\n" |
| 59 | "several -lines arguments.\n" |
| 60 | "Can't be used with -offset and -length.\n" |
| 61 | "Can only be used with one input file."), |
| 62 | cl::cat(ClangFormatCategory)); |
Alexander Kornienko | 88a0d93 | 2013-05-10 18:12:00 +0000 | [diff] [blame] | 63 | static cl::opt<std::string> |
Eric Liu | b4adc91 | 2018-06-25 16:29:19 +0000 | [diff] [blame] | 64 | Style("style", cl::desc(clang::format::StyleOptionHelpDescription), |
| 65 | cl::init(clang::format::DefaultFormatStyle), |
| 66 | cl::cat(ClangFormatCategory)); |
Alexander Kornienko | bc4ae44 | 2013-12-02 15:21:38 +0000 | [diff] [blame] | 67 | static cl::opt<std::string> |
Eric Liu | b4adc91 | 2018-06-25 16:29:19 +0000 | [diff] [blame] | 68 | FallbackStyle("fallback-style", |
| 69 | cl::desc("The name of the predefined style used as a\n" |
| 70 | "fallback in case clang-format is invoked with\n" |
| 71 | "-style=file, but can not find the .clang-format\n" |
| 72 | "file to use.\n" |
| 73 | "Use -fallback-style=none to skip formatting."), |
| 74 | cl::init(clang::format::DefaultFallbackStyle), |
| 75 | cl::cat(ClangFormatCategory)); |
Daniel Jasper | e488f5d | 2013-09-13 13:40:24 +0000 | [diff] [blame] | 76 | |
Paul Hoad | a65cfe3 | 2019-10-07 16:53:35 +0000 | [diff] [blame] | 77 | static cl::opt<std::string> AssumeFileName( |
| 78 | "assume-filename", |
| 79 | cl::desc("When reading from stdin, clang-format assumes this\n" |
| 80 | "filename to look for a style config file (with\n" |
| 81 | "-style=file) and to determine the language."), |
| 82 | cl::init("<stdin>"), cl::cat(ClangFormatCategory)); |
Daniel Jasper | e488f5d | 2013-09-13 13:40:24 +0000 | [diff] [blame] | 83 | |
Alexander Kornienko | 88a0d93 | 2013-05-10 18:12:00 +0000 | [diff] [blame] | 84 | static cl::opt<bool> Inplace("i", |
| 85 | cl::desc("Inplace edit <file>s, if specified."), |
| 86 | cl::cat(ClangFormatCategory)); |
| 87 | |
| 88 | static cl::opt<bool> OutputXML("output-replacements-xml", |
| 89 | cl::desc("Output replacements as XML."), |
| 90 | cl::cat(ClangFormatCategory)); |
Alexander Kornienko | 4914967 | 2013-05-10 11:56:10 +0000 | [diff] [blame] | 91 | static cl::opt<bool> |
| 92 | DumpConfig("dump-config", |
Alexander Kornienko | 88a0d93 | 2013-05-10 18:12:00 +0000 | [diff] [blame] | 93 | cl::desc("Dump configuration options to stdout and exit.\n" |
| 94 | "Can be used with -style option."), |
| 95 | cl::cat(ClangFormatCategory)); |
Daniel Jasper | 2a250b8 | 2013-05-21 12:21:39 +0000 | [diff] [blame] | 96 | static cl::opt<unsigned> |
| 97 | Cursor("cursor", |
Alexander Kornienko | d83adf3 | 2013-09-02 15:30:26 +0000 | [diff] [blame] | 98 | cl::desc("The position of the cursor when invoking\n" |
| 99 | "clang-format from an editor integration"), |
Daniel Jasper | 2a250b8 | 2013-05-21 12:21:39 +0000 | [diff] [blame] | 100 | cl::init(0), cl::cat(ClangFormatCategory)); |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 101 | |
Daniel Jasper | da44677 | 2015-11-16 12:38:56 +0000 | [diff] [blame] | 102 | static cl::opt<bool> SortIncludes( |
| 103 | "sort-includes", |
| 104 | cl::desc("If set, overrides the include sorting behavior determined by the " |
| 105 | "SortIncludes style flag"), |
| 106 | cl::cat(ClangFormatCategory)); |
Daniel Jasper | d89ae9d | 2015-09-23 08:30:47 +0000 | [diff] [blame] | 107 | |
Sylvestre Ledru | d23dd6c | 2017-08-12 15:15:10 +0000 | [diff] [blame] | 108 | static cl::opt<bool> |
| 109 | Verbose("verbose", cl::desc("If set, shows the list of processed files"), |
| 110 | cl::cat(ClangFormatCategory)); |
| 111 | |
Paul Hoad | 6a1f7d6 | 2019-10-13 14:51:45 +0000 | [diff] [blame] | 112 | // Use --dry-run to match other LLVM tools when you mean do it but don't |
| 113 | // actually do it |
| 114 | static cl::opt<bool> |
| 115 | DryRun("dry-run", |
| 116 | cl::desc("If set, do not actually make the formatting changes"), |
| 117 | cl::cat(ClangFormatCategory)); |
| 118 | |
| 119 | // Use -n as a common command as an alias for --dry-run. (git and make use -n) |
| 120 | static cl::alias DryRunShort("n", cl::desc("Alias for --dry-run"), |
| 121 | cl::cat(ClangFormatCategory), cl::aliasopt(DryRun), |
| 122 | cl::NotHidden); |
| 123 | |
| 124 | // Emulate being able to turn on/off the warning. |
| 125 | static cl::opt<bool> |
| 126 | WarnFormat("Wclang-format-violations", |
| 127 | cl::desc("Warnings about individual formatting changes needed. " |
| 128 | "Used only with --dry-run or -n"), |
| 129 | cl::init(true), cl::cat(ClangFormatCategory), cl::Hidden); |
| 130 | |
| 131 | static cl::opt<bool> |
| 132 | NoWarnFormat("Wno-clang-format-violations", |
| 133 | cl::desc("Do not warn about individual formatting changes " |
| 134 | "needed. Used only with --dry-run or -n"), |
| 135 | cl::init(false), cl::cat(ClangFormatCategory), cl::Hidden); |
| 136 | |
| 137 | static cl::opt<unsigned> ErrorLimit( |
| 138 | "ferror-limit", |
| 139 | cl::desc("Set the maximum number of clang-format errors to emit before " |
| 140 | "stopping (0 = no limit). Used only with --dry-run or -n"), |
| 141 | cl::init(0), cl::cat(ClangFormatCategory)); |
| 142 | |
| 143 | static cl::opt<bool> |
| 144 | WarningsAsErrors("Werror", |
| 145 | cl::desc("If set, changes formatting warnings to errors"), |
| 146 | cl::cat(ClangFormatCategory)); |
| 147 | |
| 148 | static cl::opt<bool> |
| 149 | ShowColors("fcolor-diagnostics", |
| 150 | cl::desc("If set, and on a color-capable terminal controls " |
| 151 | "whether or not to print diagnostics in color"), |
| 152 | cl::init(true), cl::cat(ClangFormatCategory), cl::Hidden); |
| 153 | |
| 154 | static cl::opt<bool> |
| 155 | NoShowColors("fno-color-diagnostics", |
| 156 | cl::desc("If set, and on a color-capable terminal controls " |
| 157 | "whether or not to print diagnostics in color"), |
| 158 | cl::init(false), cl::cat(ClangFormatCategory), cl::Hidden); |
| 159 | |
Alexander Kornienko | 88a0d93 | 2013-05-10 18:12:00 +0000 | [diff] [blame] | 160 | static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"), |
| 161 | cl::cat(ClangFormatCategory)); |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 162 | |
| 163 | namespace clang { |
| 164 | namespace format { |
| 165 | |
David Blaikie | 66cc07b | 2014-06-27 17:40:03 +0000 | [diff] [blame] | 166 | static FileID createInMemoryFile(StringRef FileName, MemoryBuffer *Source, |
Benjamin Kramer | 2e2351a | 2015-10-06 10:04:08 +0000 | [diff] [blame] | 167 | SourceManager &Sources, FileManager &Files, |
Jonas Devlieghere | fc51490 | 2018-10-10 13:27:25 +0000 | [diff] [blame] | 168 | llvm::vfs::InMemoryFileSystem *MemFS) { |
Benjamin Kramer | 2e2351a | 2015-10-06 10:04:08 +0000 | [diff] [blame] | 169 | MemFS->addFileNoOwn(FileName, 0, Source); |
Harlan Haskins | 8d323d1 | 2019-08-01 21:31:56 +0000 | [diff] [blame] | 170 | auto File = Files.getFile(FileName); |
| 171 | return Sources.createFileID(File ? *File : nullptr, SourceLocation(), |
Benjamin Kramer | 2e2351a | 2015-10-06 10:04:08 +0000 | [diff] [blame] | 172 | SrcMgr::C_User); |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 173 | } |
| 174 | |
Alexander Kornienko | a49732f | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 175 | // Parses <start line>:<end line> input to a pair of line numbers. |
Alexander Kornienko | 3fbee01 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 176 | // Returns true on error. |
Alexander Kornienko | a49732f | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 177 | static bool parseLineRange(StringRef Input, unsigned &FromLine, |
| 178 | unsigned &ToLine) { |
| 179 | std::pair<StringRef, StringRef> LineRange = Input.split(':'); |
| 180 | return LineRange.first.getAsInteger(0, FromLine) || |
| 181 | LineRange.second.getAsInteger(0, ToLine); |
| 182 | } |
| 183 | |
Daniel Jasper | d89ae9d | 2015-09-23 08:30:47 +0000 | [diff] [blame] | 184 | static bool fillRanges(MemoryBuffer *Code, |
| 185 | std::vector<tooling::Range> &Ranges) { |
Jonas Devlieghere | fc51490 | 2018-10-10 13:27:25 +0000 | [diff] [blame] | 186 | IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem( |
| 187 | new llvm::vfs::InMemoryFileSystem); |
Benjamin Kramer | 2e2351a | 2015-10-06 10:04:08 +0000 | [diff] [blame] | 188 | FileManager Files(FileSystemOptions(), InMemoryFileSystem); |
Daniel Jasper | d89ae9d | 2015-09-23 08:30:47 +0000 | [diff] [blame] | 189 | DiagnosticsEngine Diagnostics( |
| 190 | IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), |
| 191 | new DiagnosticOptions); |
| 192 | SourceManager Sources(Diagnostics, Files); |
Benjamin Kramer | 2e2351a | 2015-10-06 10:04:08 +0000 | [diff] [blame] | 193 | FileID ID = createInMemoryFile("<irrelevant>", Code, Sources, Files, |
| 194 | InMemoryFileSystem.get()); |
Alexander Kornienko | a49732f | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 195 | if (!LineRanges.empty()) { |
| 196 | if (!Offsets.empty() || !Lengths.empty()) { |
Daniel Jasper | b68aabf | 2015-11-23 08:36:35 +0000 | [diff] [blame] | 197 | errs() << "error: cannot use -lines with -offset/-length\n"; |
Alexander Kornienko | a49732f | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 198 | return true; |
| 199 | } |
| 200 | |
| 201 | for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) { |
| 202 | unsigned FromLine, ToLine; |
| 203 | if (parseLineRange(LineRanges[i], FromLine, ToLine)) { |
Daniel Jasper | b68aabf | 2015-11-23 08:36:35 +0000 | [diff] [blame] | 204 | errs() << "error: invalid <start line>:<end line> pair\n"; |
Alexander Kornienko | a49732f | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 205 | return true; |
| 206 | } |
| 207 | if (FromLine > ToLine) { |
Daniel Jasper | b68aabf | 2015-11-23 08:36:35 +0000 | [diff] [blame] | 208 | errs() << "error: start line should be less than end line\n"; |
Alexander Kornienko | a49732f | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 209 | return true; |
| 210 | } |
| 211 | SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1); |
| 212 | SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX); |
| 213 | if (Start.isInvalid() || End.isInvalid()) |
| 214 | return true; |
Daniel Jasper | d89ae9d | 2015-09-23 08:30:47 +0000 | [diff] [blame] | 215 | unsigned Offset = Sources.getFileOffset(Start); |
| 216 | unsigned Length = Sources.getFileOffset(End) - Offset; |
| 217 | Ranges.push_back(tooling::Range(Offset, Length)); |
Alexander Kornienko | a49732f | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 218 | } |
| 219 | return false; |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 220 | } |
Alexander Kornienko | a49732f | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 221 | |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 222 | if (Offsets.empty()) |
| 223 | Offsets.push_back(0); |
| 224 | if (Offsets.size() != Lengths.size() && |
| 225 | !(Offsets.size() == 1 && Lengths.empty())) { |
Daniel Jasper | b68aabf | 2015-11-23 08:36:35 +0000 | [diff] [blame] | 226 | errs() << "error: number of -offset and -length arguments must match.\n"; |
Alexander Kornienko | 3fbee01 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 227 | return true; |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 228 | } |
Alexander Kornienko | 3fbee01 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 229 | for (unsigned i = 0, e = Offsets.size(); i != e; ++i) { |
| 230 | if (Offsets[i] >= Code->getBufferSize()) { |
Daniel Jasper | b68aabf | 2015-11-23 08:36:35 +0000 | [diff] [blame] | 231 | errs() << "error: offset " << Offsets[i] << " is outside the file\n"; |
Alexander Kornienko | 3fbee01 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 232 | return true; |
| 233 | } |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 234 | SourceLocation Start = |
| 235 | Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]); |
| 236 | SourceLocation End; |
| 237 | if (i < Lengths.size()) { |
Alexander Kornienko | 3fbee01 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 238 | if (Offsets[i] + Lengths[i] > Code->getBufferSize()) { |
Daniel Jasper | b68aabf | 2015-11-23 08:36:35 +0000 | [diff] [blame] | 239 | errs() << "error: invalid length " << Lengths[i] |
| 240 | << ", offset + length (" << Offsets[i] + Lengths[i] |
| 241 | << ") is outside the file.\n"; |
Alexander Kornienko | 3fbee01 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 242 | return true; |
| 243 | } |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 244 | End = Start.getLocWithOffset(Lengths[i]); |
| 245 | } else { |
| 246 | End = Sources.getLocForEndOfFile(ID); |
| 247 | } |
Daniel Jasper | d89ae9d | 2015-09-23 08:30:47 +0000 | [diff] [blame] | 248 | unsigned Offset = Sources.getFileOffset(Start); |
| 249 | unsigned Length = Sources.getFileOffset(End) - Offset; |
| 250 | Ranges.push_back(tooling::Range(Offset, Length)); |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 251 | } |
Alexander Kornienko | a49732f | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 252 | return false; |
| 253 | } |
| 254 | |
Manuel Klimek | f54dcbc | 2013-12-03 09:46:06 +0000 | [diff] [blame] | 255 | static void outputReplacementXML(StringRef Text) { |
Daniel Jasper | f39757d | 2015-10-15 18:39:31 +0000 | [diff] [blame] | 256 | // FIXME: When we sort includes, we need to make sure the stream is correct |
| 257 | // utf-8. |
Manuel Klimek | f54dcbc | 2013-12-03 09:46:06 +0000 | [diff] [blame] | 258 | size_t From = 0; |
| 259 | size_t Index; |
Daniel Jasper | f39757d | 2015-10-15 18:39:31 +0000 | [diff] [blame] | 260 | while ((Index = Text.find_first_of("\n\r<&", From)) != StringRef::npos) { |
Daniel Jasper | b68aabf | 2015-11-23 08:36:35 +0000 | [diff] [blame] | 261 | outs() << Text.substr(From, Index - From); |
Manuel Klimek | f54dcbc | 2013-12-03 09:46:06 +0000 | [diff] [blame] | 262 | switch (Text[Index]) { |
| 263 | case '\n': |
Daniel Jasper | b68aabf | 2015-11-23 08:36:35 +0000 | [diff] [blame] | 264 | outs() << " "; |
Manuel Klimek | f54dcbc | 2013-12-03 09:46:06 +0000 | [diff] [blame] | 265 | break; |
| 266 | case '\r': |
Daniel Jasper | b68aabf | 2015-11-23 08:36:35 +0000 | [diff] [blame] | 267 | outs() << " "; |
Manuel Klimek | f54dcbc | 2013-12-03 09:46:06 +0000 | [diff] [blame] | 268 | break; |
Daniel Jasper | f39757d | 2015-10-15 18:39:31 +0000 | [diff] [blame] | 269 | case '<': |
Daniel Jasper | b68aabf | 2015-11-23 08:36:35 +0000 | [diff] [blame] | 270 | outs() << "<"; |
Daniel Jasper | f39757d | 2015-10-15 18:39:31 +0000 | [diff] [blame] | 271 | break; |
| 272 | case '&': |
Daniel Jasper | b68aabf | 2015-11-23 08:36:35 +0000 | [diff] [blame] | 273 | outs() << "&"; |
Daniel Jasper | f39757d | 2015-10-15 18:39:31 +0000 | [diff] [blame] | 274 | break; |
Manuel Klimek | f54dcbc | 2013-12-03 09:46:06 +0000 | [diff] [blame] | 275 | default: |
| 276 | llvm_unreachable("Unexpected character encountered!"); |
| 277 | } |
| 278 | From = Index + 1; |
| 279 | } |
Daniel Jasper | b68aabf | 2015-11-23 08:36:35 +0000 | [diff] [blame] | 280 | outs() << Text.substr(From); |
Manuel Klimek | f54dcbc | 2013-12-03 09:46:06 +0000 | [diff] [blame] | 281 | } |
| 282 | |
Daniel Jasper | d89ae9d | 2015-09-23 08:30:47 +0000 | [diff] [blame] | 283 | static void outputReplacementsXML(const Replacements &Replaces) { |
| 284 | for (const auto &R : Replaces) { |
| 285 | outs() << "<replacement " |
| 286 | << "offset='" << R.getOffset() << "' " |
| 287 | << "length='" << R.getLength() << "'>"; |
| 288 | outputReplacementXML(R.getReplacementText()); |
| 289 | outs() << "</replacement>\n"; |
| 290 | } |
| 291 | } |
| 292 | |
Paul Hoad | 6a1f7d6 | 2019-10-13 14:51:45 +0000 | [diff] [blame] | 293 | static bool |
| 294 | emitReplacementWarnings(const Replacements &Replaces, StringRef AssumedFileName, |
| 295 | const std::unique_ptr<llvm::MemoryBuffer> &Code) { |
| 296 | if (Replaces.empty()) { |
| 297 | return false; |
| 298 | } |
| 299 | |
| 300 | IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); |
| 301 | DiagOpts->ShowColors = (ShowColors && !NoShowColors); |
| 302 | |
Vlad Tsyrklevich | efed314 | 2019-10-29 10:20:38 -0700 | [diff] [blame] | 303 | TextDiagnosticPrinter *DiagsBuffer = |
| 304 | new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts, false); |
| 305 | |
Paul Hoad | 6a1f7d6 | 2019-10-13 14:51:45 +0000 | [diff] [blame] | 306 | IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); |
| 307 | IntrusiveRefCntPtr<DiagnosticsEngine> Diags( |
Vlad Tsyrklevich | efed314 | 2019-10-29 10:20:38 -0700 | [diff] [blame] | 308 | new DiagnosticsEngine(DiagID, &*DiagOpts, DiagsBuffer)); |
Paul Hoad | 6a1f7d6 | 2019-10-13 14:51:45 +0000 | [diff] [blame] | 309 | |
| 310 | IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem( |
| 311 | new llvm::vfs::InMemoryFileSystem); |
| 312 | FileManager Files(FileSystemOptions(), InMemoryFileSystem); |
| 313 | SourceManager Sources(*Diags, Files); |
| 314 | FileID FileID = createInMemoryFile(AssumedFileName, Code.get(), Sources, |
| 315 | Files, InMemoryFileSystem.get()); |
| 316 | |
Vlad Tsyrklevich | efed314 | 2019-10-29 10:20:38 -0700 | [diff] [blame] | 317 | const unsigned ID = Diags->getCustomDiagID( |
| 318 | WarningsAsErrors ? clang::DiagnosticsEngine::Error |
| 319 | : clang::DiagnosticsEngine::Warning, |
| 320 | "code should be clang-formatted [-Wclang-format-violations]"); |
Paul Hoad | 6a1f7d6 | 2019-10-13 14:51:45 +0000 | [diff] [blame] | 321 | |
| 322 | unsigned Errors = 0; |
Vlad Tsyrklevich | efed314 | 2019-10-29 10:20:38 -0700 | [diff] [blame] | 323 | DiagsBuffer->BeginSourceFile(LangOptions(), nullptr); |
Paul Hoad | 6a1f7d6 | 2019-10-13 14:51:45 +0000 | [diff] [blame] | 324 | if (WarnFormat && !NoWarnFormat) { |
| 325 | for (const auto &R : Replaces) { |
Vlad Tsyrklevich | efed314 | 2019-10-29 10:20:38 -0700 | [diff] [blame] | 326 | Diags->Report( |
| 327 | Sources.getLocForStartOfFile(FileID).getLocWithOffset(R.getOffset()), |
| 328 | ID); |
Paul Hoad | 6a1f7d6 | 2019-10-13 14:51:45 +0000 | [diff] [blame] | 329 | Errors++; |
| 330 | if (ErrorLimit && Errors >= ErrorLimit) |
| 331 | break; |
| 332 | } |
| 333 | } |
Vlad Tsyrklevich | efed314 | 2019-10-29 10:20:38 -0700 | [diff] [blame] | 334 | DiagsBuffer->EndSourceFile(); |
Paul Hoad | 6a1f7d6 | 2019-10-13 14:51:45 +0000 | [diff] [blame] | 335 | return WarningsAsErrors; |
| 336 | } |
| 337 | |
| 338 | static void outputXML(const Replacements &Replaces, |
| 339 | const Replacements &FormatChanges, |
| 340 | const FormattingAttemptStatus &Status, |
| 341 | const cl::opt<unsigned> &Cursor, |
| 342 | unsigned CursorPosition) { |
| 343 | outs() << "<?xml version='1.0'?>\n<replacements " |
| 344 | "xml:space='preserve' incomplete_format='" |
| 345 | << (Status.FormatComplete ? "false" : "true") << "'"; |
| 346 | if (!Status.FormatComplete) |
| 347 | outs() << " line='" << Status.Line << "'"; |
| 348 | outs() << ">\n"; |
| 349 | if (Cursor.getNumOccurrences() != 0) |
| 350 | outs() << "<cursor>" << FormatChanges.getShiftedCodePosition(CursorPosition) |
| 351 | << "</cursor>\n"; |
| 352 | |
| 353 | outputReplacementsXML(Replaces); |
| 354 | outs() << "</replacements>\n"; |
| 355 | } |
| 356 | |
Alexander Kornienko | a49732f | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 357 | // Returns true on error. |
Bill Wendling | e94f74f | 2013-11-09 00:23:58 +0000 | [diff] [blame] | 358 | static bool format(StringRef FileName) { |
Nico Weber | 65da457 | 2017-02-27 22:59:58 +0000 | [diff] [blame] | 359 | if (!OutputXML && Inplace && FileName == "-") { |
| 360 | errs() << "error: cannot use -i when reading from stdin.\n"; |
| 361 | return false; |
| 362 | } |
| 363 | // On Windows, overwriting a file with an open file mapping doesn't work, |
| 364 | // so read the whole file into memory when formatting in-place. |
Rafael Espindola | 2d2b420 | 2014-07-06 17:43:24 +0000 | [diff] [blame] | 365 | ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr = |
Paul Hoad | a65cfe3 | 2019-10-07 16:53:35 +0000 | [diff] [blame] | 366 | !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName) |
| 367 | : MemoryBuffer::getFileOrSTDIN(FileName); |
Rafael Espindola | 2d2b420 | 2014-07-06 17:43:24 +0000 | [diff] [blame] | 368 | if (std::error_code EC = CodeOrErr.getError()) { |
Daniel Jasper | b68aabf | 2015-11-23 08:36:35 +0000 | [diff] [blame] | 369 | errs() << EC.message() << "\n"; |
Alexander Kornienko | a49732f | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 370 | return true; |
| 371 | } |
Rafael Espindola | 2d2b420 | 2014-07-06 17:43:24 +0000 | [diff] [blame] | 372 | std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get()); |
Alexander Kornienko | a49732f | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 373 | if (Code->getBufferSize() == 0) |
Daniel Jasper | e8845ad | 2013-10-08 15:54:36 +0000 | [diff] [blame] | 374 | return false; // Empty files are formatted correctly. |
Owen Pan | 4ba5269 | 2019-05-08 14:11:12 +0000 | [diff] [blame] | 375 | |
Owen Pan | 4ba5269 | 2019-05-08 14:11:12 +0000 | [diff] [blame] | 376 | StringRef BufStr = Code->getBuffer(); |
Paul Hoad | 6a1f7d6 | 2019-10-13 14:51:45 +0000 | [diff] [blame] | 377 | |
paulhoad | 8fa5e98 | 2019-10-24 20:24:03 +0100 | [diff] [blame] | 378 | const char *InvalidBOM = SrcMgr::ContentCache::getInvalidBOM(BufStr); |
Owen Pan | 4ba5269 | 2019-05-08 14:11:12 +0000 | [diff] [blame] | 379 | |
| 380 | if (InvalidBOM) { |
| 381 | errs() << "error: encoding with unsupported byte order mark \"" |
| 382 | << InvalidBOM << "\" detected"; |
| 383 | if (FileName != "-") |
| 384 | errs() << " in file '" << FileName << "'"; |
| 385 | errs() << ".\n"; |
| 386 | return true; |
| 387 | } |
| 388 | |
Daniel Jasper | d89ae9d | 2015-09-23 08:30:47 +0000 | [diff] [blame] | 389 | std::vector<tooling::Range> Ranges; |
| 390 | if (fillRanges(Code.get(), Ranges)) |
Alexander Kornienko | a49732f | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 391 | return true; |
Daniel Jasper | 85c472d | 2015-09-29 07:53:08 +0000 | [diff] [blame] | 392 | StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName; |
Antonio Maiorano | 3adfb6a | 2017-01-17 00:12:27 +0000 | [diff] [blame] | 393 | |
| 394 | llvm::Expected<FormatStyle> FormatStyle = |
Daniel Jasper | 03a04fe | 2016-12-12 12:42:29 +0000 | [diff] [blame] | 395 | getStyle(Style, AssumedFileName, FallbackStyle, Code->getBuffer()); |
Antonio Maiorano | 3adfb6a | 2017-01-17 00:12:27 +0000 | [diff] [blame] | 396 | if (!FormatStyle) { |
| 397 | llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n"; |
| 398 | return true; |
| 399 | } |
Martin Probst | fa37b18 | 2017-01-27 09:09:11 +0000 | [diff] [blame] | 400 | |
Daniel Jasper | da44677 | 2015-11-16 12:38:56 +0000 | [diff] [blame] | 401 | if (SortIncludes.getNumOccurrences() != 0) |
Antonio Maiorano | 3adfb6a | 2017-01-17 00:12:27 +0000 | [diff] [blame] | 402 | FormatStyle->SortIncludes = SortIncludes; |
Daniel Jasper | b68aabf | 2015-11-23 08:36:35 +0000 | [diff] [blame] | 403 | unsigned CursorPosition = Cursor; |
Antonio Maiorano | 3adfb6a | 2017-01-17 00:12:27 +0000 | [diff] [blame] | 404 | Replacements Replaces = sortIncludes(*FormatStyle, Code->getBuffer(), Ranges, |
Daniel Jasper | b68aabf | 2015-11-23 08:36:35 +0000 | [diff] [blame] | 405 | AssumedFileName, &CursorPosition); |
Eric Liu | 4f8d994 | 2016-07-11 13:53:12 +0000 | [diff] [blame] | 406 | auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces); |
| 407 | if (!ChangedCode) { |
| 408 | llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n"; |
| 409 | return true; |
| 410 | } |
Eric Liu | a992afe | 2016-08-10 09:32:23 +0000 | [diff] [blame] | 411 | // Get new affected ranges after sorting `#includes`. |
| 412 | Ranges = tooling::calculateRangesAfterReplacements(Replaces, Ranges); |
Krasimir Georgiev | bcda54b | 2017-04-21 14:35:20 +0000 | [diff] [blame] | 413 | FormattingAttemptStatus Status; |
Paul Hoad | a65cfe3 | 2019-10-07 16:53:35 +0000 | [diff] [blame] | 414 | Replacements FormatChanges = |
| 415 | reformat(*FormatStyle, *ChangedCode, Ranges, AssumedFileName, &Status); |
Eric Liu | 40ef2fb | 2016-08-01 10:16:37 +0000 | [diff] [blame] | 416 | Replaces = Replaces.merge(FormatChanges); |
Paul Hoad | 6a1f7d6 | 2019-10-13 14:51:45 +0000 | [diff] [blame] | 417 | if (OutputXML || DryRun) { |
| 418 | if (DryRun) { |
| 419 | return emitReplacementWarnings(Replaces, AssumedFileName, Code); |
| 420 | } else { |
| 421 | outputXML(Replaces, FormatChanges, Status, Cursor, CursorPosition); |
| 422 | } |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 423 | } else { |
Jonas Devlieghere | fc51490 | 2018-10-10 13:27:25 +0000 | [diff] [blame] | 424 | IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem( |
| 425 | new llvm::vfs::InMemoryFileSystem); |
Benjamin Kramer | 2e2351a | 2015-10-06 10:04:08 +0000 | [diff] [blame] | 426 | FileManager Files(FileSystemOptions(), InMemoryFileSystem); |
Daniel Jasper | 867a938 | 2015-09-30 13:59:29 +0000 | [diff] [blame] | 427 | DiagnosticsEngine Diagnostics( |
| 428 | IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), |
| 429 | new DiagnosticOptions); |
| 430 | SourceManager Sources(Diagnostics, Files); |
Benjamin Kramer | 2e2351a | 2015-10-06 10:04:08 +0000 | [diff] [blame] | 431 | FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files, |
| 432 | InMemoryFileSystem.get()); |
Daniel Jasper | 867a938 | 2015-09-30 13:59:29 +0000 | [diff] [blame] | 433 | Rewriter Rewrite(Sources, LangOptions()); |
| 434 | tooling::applyAllReplacements(Replaces, Rewrite); |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 435 | if (Inplace) { |
Nico Weber | 65da457 | 2017-02-27 22:59:58 +0000 | [diff] [blame] | 436 | if (Rewrite.overwriteChangedFiles()) |
Daniel Jasper | 867a938 | 2015-09-30 13:59:29 +0000 | [diff] [blame] | 437 | return true; |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 438 | } else { |
Krasimir Georgiev | bcda54b | 2017-04-21 14:35:20 +0000 | [diff] [blame] | 439 | if (Cursor.getNumOccurrences() != 0) { |
Tobias Grosser | a704600 | 2015-05-08 21:34:09 +0000 | [diff] [blame] | 440 | outs() << "{ \"Cursor\": " |
Eric Liu | 40ef2fb | 2016-08-01 10:16:37 +0000 | [diff] [blame] | 441 | << FormatChanges.getShiftedCodePosition(CursorPosition) |
Daniel Jasper | 622c72d | 2015-05-10 07:47:19 +0000 | [diff] [blame] | 442 | << ", \"IncompleteFormat\": " |
Krasimir Georgiev | bcda54b | 2017-04-21 14:35:20 +0000 | [diff] [blame] | 443 | << (Status.FormatComplete ? "false" : "true"); |
| 444 | if (!Status.FormatComplete) |
| 445 | outs() << ", \"Line\": " << Status.Line; |
| 446 | outs() << " }\n"; |
| 447 | } |
Daniel Jasper | 867a938 | 2015-09-30 13:59:29 +0000 | [diff] [blame] | 448 | Rewrite.getEditBuffer(ID).write(outs()); |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 449 | } |
| 450 | } |
Alexander Kornienko | 3fbee01 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 451 | return false; |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 452 | } |
| 453 | |
Paul Hoad | a65cfe3 | 2019-10-07 16:53:35 +0000 | [diff] [blame] | 454 | } // namespace format |
| 455 | } // namespace clang |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 456 | |
Dimitry Andric | 81c4042 | 2017-06-06 21:54:21 +0000 | [diff] [blame] | 457 | static void PrintVersion(raw_ostream &OS) { |
Nico Weber | b00d66e | 2014-01-07 16:27:35 +0000 | [diff] [blame] | 458 | OS << clang::getClangToolFullVersion("clang-format") << '\n'; |
| 459 | } |
| 460 | |
Paul Hoad | 6a1f7d6 | 2019-10-13 14:51:45 +0000 | [diff] [blame] | 461 | // Dump the configuration. |
| 462 | static int dumpConfig() { |
| 463 | StringRef FileName; |
| 464 | std::unique_ptr<llvm::MemoryBuffer> Code; |
| 465 | if (FileNames.empty()) { |
| 466 | // We can't read the code to detect the language if there's no |
| 467 | // file name, so leave Code empty here. |
| 468 | FileName = AssumeFileName; |
| 469 | } else { |
| 470 | // Read in the code in case the filename alone isn't enough to |
| 471 | // detect the language. |
| 472 | ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr = |
| 473 | MemoryBuffer::getFileOrSTDIN(FileNames[0]); |
| 474 | if (std::error_code EC = CodeOrErr.getError()) { |
| 475 | llvm::errs() << EC.message() << "\n"; |
| 476 | return 1; |
| 477 | } |
| 478 | FileName = (FileNames[0] == "-") ? AssumeFileName : FileNames[0]; |
| 479 | Code = std::move(CodeOrErr.get()); |
| 480 | } |
| 481 | llvm::Expected<clang::format::FormatStyle> FormatStyle = |
| 482 | clang::format::getStyle(Style, FileName, FallbackStyle, |
| 483 | Code ? Code->getBuffer() : ""); |
| 484 | if (!FormatStyle) { |
| 485 | llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n"; |
| 486 | return 1; |
| 487 | } |
| 488 | std::string Config = clang::format::configurationAsText(*FormatStyle); |
| 489 | outs() << Config << "\n"; |
| 490 | return 0; |
| 491 | } |
| 492 | |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 493 | int main(int argc, const char **argv) { |
Rui Ueyama | e4b59a9 | 2018-04-13 20:57:57 +0000 | [diff] [blame] | 494 | llvm::InitLLVM X(argc, argv); |
Alexander Kornienko | 54dcb53 | 2018-03-26 13:54:17 +0000 | [diff] [blame] | 495 | |
Chris Bieneman | 0a9f607 | 2015-01-21 23:26:11 +0000 | [diff] [blame] | 496 | cl::HideUnrelatedOptions(ClangFormatCategory); |
Alexander Kornienko | 88a0d93 | 2013-05-10 18:12:00 +0000 | [diff] [blame] | 497 | |
Nico Weber | b00d66e | 2014-01-07 16:27:35 +0000 | [diff] [blame] | 498 | cl::SetVersionPrinter(PrintVersion); |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 499 | cl::ParseCommandLineOptions( |
Rui Ueyama | e4b59a9 | 2018-04-13 20:57:57 +0000 | [diff] [blame] | 500 | argc, argv, |
Paul Hoad | cbb726d | 2019-03-21 13:09:22 +0000 | [diff] [blame] | 501 | "A tool to format C/C++/Java/JavaScript/Objective-C/Protobuf/C# code.\n\n" |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 502 | "If no arguments are specified, it formats the code from standard input\n" |
| 503 | "and writes the result to the standard output.\n" |
Alexander Kornienko | d83adf3 | 2013-09-02 15:30:26 +0000 | [diff] [blame] | 504 | "If <file>s are given, it reformats the files. If -i is specified\n" |
| 505 | "together with <file>s, the files are edited in-place. Otherwise, the\n" |
Alexander Kornienko | 3fbee01 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 506 | "result is written to the standard output.\n"); |
| 507 | |
Rafael Espindola | 79d9a69 | 2017-09-08 00:01:26 +0000 | [diff] [blame] | 508 | if (Help) { |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 509 | cl::PrintHelpMessage(); |
Rafael Espindola | 79d9a69 | 2017-09-08 00:01:26 +0000 | [diff] [blame] | 510 | return 0; |
| 511 | } |
Alexander Kornienko | 3fbee01 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 512 | |
Alexander Kornienko | 4914967 | 2013-05-10 11:56:10 +0000 | [diff] [blame] | 513 | if (DumpConfig) { |
Paul Hoad | 6a1f7d6 | 2019-10-13 14:51:45 +0000 | [diff] [blame] | 514 | return dumpConfig(); |
Alexander Kornienko | 4914967 | 2013-05-10 11:56:10 +0000 | [diff] [blame] | 515 | } |
| 516 | |
Alexander Kornienko | 3fbee01 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 517 | bool Error = false; |
Sylvestre Ledru | d23dd6c | 2017-08-12 15:15:10 +0000 | [diff] [blame] | 518 | if (FileNames.empty()) { |
Alexander Kornienko | 3fbee01 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 519 | Error = clang::format::format("-"); |
Sylvestre Ledru | d23dd6c | 2017-08-12 15:15:10 +0000 | [diff] [blame] | 520 | return Error ? 1 : 0; |
| 521 | } |
Paul Hoad | a65cfe3 | 2019-10-07 16:53:35 +0000 | [diff] [blame] | 522 | if (FileNames.size() != 1 && |
| 523 | (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty())) { |
Sylvestre Ledru | d23dd6c | 2017-08-12 15:15:10 +0000 | [diff] [blame] | 524 | errs() << "error: -offset, -length and -lines can only be used for " |
| 525 | "single file.\n"; |
| 526 | return 1; |
| 527 | } |
| 528 | for (const auto &FileName : FileNames) { |
| 529 | if (Verbose) |
| 530 | errs() << "Formatting " << FileName << "\n"; |
| 531 | Error |= clang::format::format(FileName); |
Alexander Kornienko | 3fbee01 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 532 | } |
| 533 | return Error ? 1 : 0; |
Daniel Jasper | 9be2c5c | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 534 | } |