| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 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" |
| 19 | #include "clang/Basic/Version.h" |
| 20 | #include "clang/Format/Format.h" |
| 21 | #include "clang/Rewrite/Core/Rewriter.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 | |
| 27 | using namespace llvm; |
| 28 | using clang::tooling::Replacements; |
| 29 | |
| 30 | static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden); |
| 31 | |
| 32 | |
| 33 | |
| 34 | static cl::OptionCategory ClangFormatCategory("Clang-format options"); |
| 35 | |
| 36 | static cl::list<unsigned> |
| 37 | Offsets("offset", |
| 38 | cl::desc("Format a range starting at this byte offset.\n" |
| 39 | "Multiple ranges can be formatted by specifying\n" |
| 40 | "several -offset and -length pairs.\n" |
| 41 | "Can only be used with one input file."), |
| 42 | cl::cat(ClangFormatCategory)); |
| 43 | static cl::list<unsigned> |
| 44 | Lengths("length", |
| 45 | cl::desc("Format a range of this length (in bytes).\n" |
| 46 | "Multiple ranges can be formatted by specifying\n" |
| 47 | "several -offset and -length pairs.\n" |
| 48 | "When only a single -offset is specified without\n" |
| 49 | "-length, clang-format will format up to the end\n" |
| 50 | "of the file.\n" |
| 51 | "Can only be used with one input file."), |
| 52 | cl::cat(ClangFormatCategory)); |
| 53 | static cl::list<std::string> |
| 54 | LineRanges("lines", cl::desc("<start line>:<end line> - format a range of\n" |
| 55 | "lines (both 1-based).\n" |
| 56 | "Multiple ranges can be formatted by specifying\n" |
| 57 | "several -lines arguments.\n" |
| 58 | "Can't be used with -offset and -length.\n" |
| 59 | "Can only be used with one input file."), |
| 60 | cl::cat(ClangFormatCategory)); |
| 61 | static cl::opt<std::string> |
| 62 | Style("style", cl::desc(clang::format::StyleOptionHelpDescription), |
| 63 | cl::init(clang::format::DefaultFormatStyle), |
| 64 | cl::cat(ClangFormatCategory)); |
| 65 | static cl::opt<std::string> |
| 66 | FallbackStyle("fallback-style", |
| 67 | cl::desc("The name of the predefined style used as a\n" |
| 68 | "fallback in case clang-format is invoked with\n" |
| 69 | "-style=file, but can not find the .clang-format\n" |
| 70 | "file to use.\n" |
| 71 | "Use -fallback-style=none to skip formatting."), |
| 72 | cl::init(clang::format::DefaultFallbackStyle), |
| 73 | cl::cat(ClangFormatCategory)); |
| 74 | |
| 75 | static cl::opt<std::string> |
| 76 | AssumeFileName("assume-filename", |
| 77 | cl::desc("When reading from stdin, clang-format assumes this\n" |
| 78 | "filename to look for a style config file (with\n" |
| 79 | "-style=file) and to determine the language."), |
| 80 | cl::init("<stdin>"), cl::cat(ClangFormatCategory)); |
| 81 | |
| 82 | static cl::opt<bool> Inplace("i", |
| 83 | cl::desc("Inplace edit <file>s, if specified."), |
| 84 | cl::cat(ClangFormatCategory)); |
| 85 | |
| 86 | static cl::opt<bool> OutputXML("output-replacements-xml", |
| 87 | cl::desc("Output replacements as XML."), |
| 88 | cl::cat(ClangFormatCategory)); |
| 89 | static cl::opt<bool> |
| 90 | DumpConfig("dump-config", |
| 91 | cl::desc("Dump configuration options to stdout and exit.\n" |
| 92 | "Can be used with -style option."), |
| 93 | cl::cat(ClangFormatCategory)); |
| 94 | static cl::opt<unsigned> |
| 95 | Cursor("cursor", |
| 96 | cl::desc("The position of the cursor when invoking\n" |
| 97 | "clang-format from an editor integration"), |
| 98 | cl::init(0), cl::cat(ClangFormatCategory)); |
| 99 | |
| 100 | static cl::opt<bool> SortIncludes( |
| 101 | "sort-includes", |
| 102 | cl::desc("If set, overrides the include sorting behavior determined by the " |
| 103 | "SortIncludes style flag"), |
| 104 | cl::cat(ClangFormatCategory)); |
| 105 | |
| 106 | static cl::opt<bool> |
| 107 | Verbose("verbose", cl::desc("If set, shows the list of processed files"), |
| 108 | cl::cat(ClangFormatCategory)); |
| 109 | |
| 110 | static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"), |
| 111 | cl::cat(ClangFormatCategory)); |
| 112 | |
| 113 | namespace clang { |
| 114 | namespace format { |
| 115 | |
| 116 | static FileID createInMemoryFile(StringRef FileName, MemoryBuffer *Source, |
| 117 | SourceManager &Sources, FileManager &Files, |
| 118 | llvm::vfs::InMemoryFileSystem *MemFS) { |
| 119 | MemFS->addFileNoOwn(FileName, 0, Source); |
| 120 | return Sources.createFileID(Files.getFile(FileName), SourceLocation(), |
| 121 | SrcMgr::C_User); |
| 122 | } |
| 123 | |
| 124 | |
| 125 | |
| 126 | static bool parseLineRange(StringRef Input, unsigned &FromLine, |
| 127 | unsigned &ToLine) { |
| 128 | std::pair<StringRef, StringRef> LineRange = Input.split(':'); |
| 129 | return LineRange.first.getAsInteger(0, FromLine) || |
| 130 | LineRange.second.getAsInteger(0, ToLine); |
| 131 | } |
| 132 | |
| 133 | static bool fillRanges(MemoryBuffer *Code, |
| 134 | std::vector<tooling::Range> &Ranges) { |
| 135 | IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem( |
| 136 | new llvm::vfs::InMemoryFileSystem); |
| 137 | FileManager Files(FileSystemOptions(), InMemoryFileSystem); |
| 138 | DiagnosticsEngine Diagnostics( |
| 139 | IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), |
| 140 | new DiagnosticOptions); |
| 141 | SourceManager Sources(Diagnostics, Files); |
| 142 | FileID ID = createInMemoryFile("<irrelevant>", Code, Sources, Files, |
| 143 | InMemoryFileSystem.get()); |
| 144 | if (!LineRanges.empty()) { |
| 145 | if (!Offsets.empty() || !Lengths.empty()) { |
| 146 | errs() << "error: cannot use -lines with -offset/-length\n"; |
| 147 | return true; |
| 148 | } |
| 149 | |
| 150 | for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) { |
| 151 | unsigned FromLine, ToLine; |
| 152 | if (parseLineRange(LineRanges[i], FromLine, ToLine)) { |
| 153 | errs() << "error: invalid <start line>:<end line> pair\n"; |
| 154 | return true; |
| 155 | } |
| 156 | if (FromLine > ToLine) { |
| 157 | errs() << "error: start line should be less than end line\n"; |
| 158 | return true; |
| 159 | } |
| 160 | SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1); |
| 161 | SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX); |
| 162 | if (Start.isInvalid() || End.isInvalid()) |
| 163 | return true; |
| 164 | unsigned Offset = Sources.getFileOffset(Start); |
| 165 | unsigned Length = Sources.getFileOffset(End) - Offset; |
| 166 | Ranges.push_back(tooling::Range(Offset, Length)); |
| 167 | } |
| 168 | return false; |
| 169 | } |
| 170 | |
| 171 | if (Offsets.empty()) |
| 172 | Offsets.push_back(0); |
| 173 | if (Offsets.size() != Lengths.size() && |
| 174 | !(Offsets.size() == 1 && Lengths.empty())) { |
| 175 | errs() << "error: number of -offset and -length arguments must match.\n"; |
| 176 | return true; |
| 177 | } |
| 178 | for (unsigned i = 0, e = Offsets.size(); i != e; ++i) { |
| 179 | if (Offsets[i] >= Code->getBufferSize()) { |
| 180 | errs() << "error: offset " << Offsets[i] << " is outside the file\n"; |
| 181 | return true; |
| 182 | } |
| 183 | SourceLocation Start = |
| 184 | Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]); |
| 185 | SourceLocation End; |
| 186 | if (i < Lengths.size()) { |
| 187 | if (Offsets[i] + Lengths[i] > Code->getBufferSize()) { |
| 188 | errs() << "error: invalid length " << Lengths[i] |
| 189 | << ", offset + length (" << Offsets[i] + Lengths[i] |
| 190 | << ") is outside the file.\n"; |
| 191 | return true; |
| 192 | } |
| 193 | End = Start.getLocWithOffset(Lengths[i]); |
| 194 | } else { |
| 195 | End = Sources.getLocForEndOfFile(ID); |
| 196 | } |
| 197 | unsigned Offset = Sources.getFileOffset(Start); |
| 198 | unsigned Length = Sources.getFileOffset(End) - Offset; |
| 199 | Ranges.push_back(tooling::Range(Offset, Length)); |
| 200 | } |
| 201 | return false; |
| 202 | } |
| 203 | |
| 204 | static void outputReplacementXML(StringRef Text) { |
| 205 | |
| 206 | |
| 207 | size_t From = 0; |
| 208 | size_t Index; |
| 209 | while ((Index = Text.find_first_of("\n\r<&", From)) != StringRef::npos) { |
| 210 | outs() << Text.substr(From, Index - From); |
| 211 | switch (Text[Index]) { |
| 212 | case '\n': |
| 213 | outs() << " "; |
| 214 | break; |
| 215 | case '\r': |
| 216 | outs() << " "; |
| 217 | break; |
| 218 | case '<': |
| 219 | outs() << "<"; |
| 220 | break; |
| 221 | case '&': |
| 222 | outs() << "&"; |
| 223 | break; |
| 224 | default: |
| 225 | llvm_unreachable("Unexpected character encountered!"); |
| 226 | } |
| 227 | From = Index + 1; |
| 228 | } |
| 229 | outs() << Text.substr(From); |
| 230 | } |
| 231 | |
| 232 | static void outputReplacementsXML(const Replacements &Replaces) { |
| 233 | for (const auto &R : Replaces) { |
| 234 | outs() << "<replacement " |
| 235 | << "offset='" << R.getOffset() << "' " |
| 236 | << "length='" << R.getLength() << "'>"; |
| 237 | outputReplacementXML(R.getReplacementText()); |
| 238 | outs() << "</replacement>\n"; |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | |
| 243 | static bool format(StringRef FileName) { |
| 244 | if (!OutputXML && Inplace && FileName == "-") { |
| 245 | errs() << "error: cannot use -i when reading from stdin.\n"; |
| 246 | return false; |
| 247 | } |
| 248 | |
| 249 | |
| 250 | ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr = |
| 251 | !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName) : |
| 252 | MemoryBuffer::getFileOrSTDIN(FileName); |
| 253 | if (std::error_code EC = CodeOrErr.getError()) { |
| 254 | errs() << EC.message() << "\n"; |
| 255 | return true; |
| 256 | } |
| 257 | std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get()); |
| 258 | if (Code->getBufferSize() == 0) |
| 259 | return false; |
| 260 | std::vector<tooling::Range> Ranges; |
| 261 | if (fillRanges(Code.get(), Ranges)) |
| 262 | return true; |
| 263 | StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName; |
| 264 | |
| 265 | llvm::Expected<FormatStyle> FormatStyle = |
| 266 | getStyle(Style, AssumedFileName, FallbackStyle, Code->getBuffer()); |
| 267 | if (!FormatStyle) { |
| 268 | llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n"; |
| 269 | return true; |
| 270 | } |
| 271 | |
| 272 | if (SortIncludes.getNumOccurrences() != 0) |
| 273 | FormatStyle->SortIncludes = SortIncludes; |
| 274 | unsigned CursorPosition = Cursor; |
| 275 | Replacements Replaces = sortIncludes(*FormatStyle, Code->getBuffer(), Ranges, |
| 276 | AssumedFileName, &CursorPosition); |
| 277 | auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces); |
| 278 | if (!ChangedCode) { |
| 279 | llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n"; |
| 280 | return true; |
| 281 | } |
| 282 | |
| 283 | Ranges = tooling::calculateRangesAfterReplacements(Replaces, Ranges); |
| 284 | FormattingAttemptStatus Status; |
| 285 | Replacements FormatChanges = reformat(*FormatStyle, *ChangedCode, Ranges, |
| 286 | AssumedFileName, &Status); |
| 287 | Replaces = Replaces.merge(FormatChanges); |
| 288 | if (OutputXML) { |
| 289 | outs() << "<?xml version='1.0'?>\n<replacements " |
| 290 | "xml:space='preserve' incomplete_format='" |
| 291 | << (Status.FormatComplete ? "false" : "true") << "'"; |
| 292 | if (!Status.FormatComplete) |
| 293 | outs() << " line='" << Status.Line << "'"; |
| 294 | outs() << ">\n"; |
| 295 | if (Cursor.getNumOccurrences() != 0) |
| 296 | outs() << "<cursor>" |
| 297 | << FormatChanges.getShiftedCodePosition(CursorPosition) |
| 298 | << "</cursor>\n"; |
| 299 | |
| 300 | outputReplacementsXML(Replaces); |
| 301 | outs() << "</replacements>\n"; |
| 302 | } else { |
| 303 | IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem( |
| 304 | new llvm::vfs::InMemoryFileSystem); |
| 305 | FileManager Files(FileSystemOptions(), InMemoryFileSystem); |
| 306 | DiagnosticsEngine Diagnostics( |
| 307 | IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), |
| 308 | new DiagnosticOptions); |
| 309 | SourceManager Sources(Diagnostics, Files); |
| 310 | FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files, |
| 311 | InMemoryFileSystem.get()); |
| 312 | Rewriter Rewrite(Sources, LangOptions()); |
| 313 | tooling::applyAllReplacements(Replaces, Rewrite); |
| 314 | if (Inplace) { |
| 315 | if (Rewrite.overwriteChangedFiles()) |
| 316 | return true; |
| 317 | } else { |
| 318 | if (Cursor.getNumOccurrences() != 0) { |
| 319 | outs() << "{ \"Cursor\": " |
| 320 | << FormatChanges.getShiftedCodePosition(CursorPosition) |
| 321 | << ", \"IncompleteFormat\": " |
| 322 | << (Status.FormatComplete ? "false" : "true"); |
| 323 | if (!Status.FormatComplete) |
| 324 | outs() << ", \"Line\": " << Status.Line; |
| 325 | outs() << " }\n"; |
| 326 | } |
| 327 | Rewrite.getEditBuffer(ID).write(outs()); |
| 328 | } |
| 329 | } |
| 330 | return false; |
| 331 | } |
| 332 | |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | static void PrintVersion(raw_ostream &OS) { |
| 337 | OS << clang::getClangToolFullVersion("clang-format") << '\n'; |
| 338 | } |
| 339 | |
| 340 | int main(int argc, const char **argv) { |
| 341 | llvm::InitLLVM X(argc, argv); |
| 342 | |
| 343 | cl::HideUnrelatedOptions(ClangFormatCategory); |
| 344 | |
| 345 | cl::SetVersionPrinter(PrintVersion); |
| 346 | cl::ParseCommandLineOptions( |
| 347 | argc, argv, |
| 348 | "A tool to format C/C++/Java/JavaScript/Objective-C/Protobuf/C# code.\n\n" |
| 349 | "If no arguments are specified, it formats the code from standard input\n" |
| 350 | "and writes the result to the standard output.\n" |
| 351 | "If <file>s are given, it reformats the files. If -i is specified\n" |
| 352 | "together with <file>s, the files are edited in-place. Otherwise, the\n" |
| 353 | "result is written to the standard output.\n"); |
| 354 | |
| 355 | if (Help) { |
| 356 | cl::PrintHelpMessage(); |
| 357 | return 0; |
| 358 | } |
| 359 | |
| 360 | if (DumpConfig) { |
| 361 | StringRef FileName; |
| 362 | std::unique_ptr<llvm::MemoryBuffer> Code; |
| 363 | if (FileNames.empty()) { |
| 364 | |
| 365 | |
| 366 | FileName = AssumeFileName; |
| 367 | } else { |
| 368 | |
| 369 | |
| 370 | ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr = |
| 371 | MemoryBuffer::getFileOrSTDIN(FileNames[0]); |
| 372 | if (std::error_code EC = CodeOrErr.getError()) { |
| 373 | llvm::errs() << EC.message() << "\n"; |
| 374 | return 1; |
| 375 | } |
| 376 | FileName = (FileNames[0] == "-") ? AssumeFileName : FileNames[0]; |
| 377 | Code = std::move(CodeOrErr.get()); |
| 378 | } |
| 379 | llvm::Expected<clang::format::FormatStyle> FormatStyle = |
| 380 | clang::format::getStyle(Style, FileName, FallbackStyle, |
| 381 | Code ? Code->getBuffer() : ""); |
| 382 | if (!FormatStyle) { |
| 383 | llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n"; |
| 384 | return 1; |
| 385 | } |
| 386 | std::string Config = clang::format::configurationAsText(*FormatStyle); |
| 387 | outs() << Config << "\n"; |
| 388 | return 0; |
| 389 | } |
| 390 | |
| 391 | bool Error = false; |
| 392 | if (FileNames.empty()) { |
| 393 | Error = clang::format::format("-"); |
| 394 | return Error ? 1 : 0; |
| 395 | } |
| 396 | if (FileNames.size() != 1 && (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty())) { |
| 397 | errs() << "error: -offset, -length and -lines can only be used for " |
| 398 | "single file.\n"; |
| 399 | return 1; |
| 400 | } |
| 401 | for (const auto &FileName : FileNames) { |
| 402 | if (Verbose) |
| 403 | errs() << "Formatting " << FileName << "\n"; |
| 404 | Error |= clang::format::format(FileName); |
| 405 | } |
| 406 | return Error ? 1 : 0; |
| 407 | } |
| 408 | |