djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 1 | //===-- clang-format/ClangFormat.cpp - Clang format tool ------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | /// |
| 10 | /// \file |
| 11 | /// \brief This file implements a clang-format tool that automatically formats |
| 12 | /// (fragments of) C++ code. |
| 13 | /// |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
| 16 | #include "clang/Basic/Diagnostic.h" |
| 17 | #include "clang/Basic/DiagnosticOptions.h" |
| 18 | #include "clang/Basic/FileManager.h" |
| 19 | #include "clang/Basic/SourceManager.h" |
nico | 436d02f | 2014-01-07 16:27:35 +0000 | [diff] [blame] | 20 | #include "clang/Basic/Version.h" |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 21 | #include "clang/Format/Format.h" |
| 22 | #include "clang/Lex/Lexer.h" |
| 23 | #include "clang/Rewrite/Core/Rewriter.h" |
chandlerc | d56704b | 2014-01-07 11:51:46 +0000 | [diff] [blame] | 24 | #include "llvm/ADT/StringMap.h" |
alexfh | 5988345 | 2013-05-10 11:56:10 +0000 | [diff] [blame] | 25 | #include "llvm/Support/Debug.h" |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 26 | #include "llvm/Support/FileSystem.h" |
| 27 | #include "llvm/Support/Signals.h" |
| 28 | |
| 29 | using namespace llvm; |
| 30 | |
| 31 | static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden); |
| 32 | |
alexfh | 725a9f7 | 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. |
alexfh | ebc1600 | 2014-02-05 13:42:43 +0000 | [diff] [blame^] | 35 | static cl::OptionCategory ClangFormatCategory("Clang-format options"); |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 36 | |
alexfh | 725a9f7 | 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)); |
alexfh | 6e70179 | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 54 | static cl::list<std::string> |
| 55 | LineRanges("lines", cl::desc("<start line>:<end line> - format a range of\n" |
| 56 | "lines (both 1-based).\n" |
| 57 | "Multiple ranges can be formatted by specifying\n" |
| 58 | "several -lines arguments.\n" |
| 59 | "Can't be used with -offset and -length.\n" |
| 60 | "Can only be used with one input file."), |
| 61 | cl::cat(ClangFormatCategory)); |
alexfh | 725a9f7 | 2013-05-10 18:12:00 +0000 | [diff] [blame] | 62 | static cl::opt<std::string> |
| 63 | Style("style", |
revane | 4d11869 | 2013-09-30 13:31:48 +0000 | [diff] [blame] | 64 | cl::desc(clang::format::StyleOptionHelpDescription), |
chandlerc | e6992fd | 2013-09-02 07:42:02 +0000 | [diff] [blame] | 65 | cl::init("file"), cl::cat(ClangFormatCategory)); |
alexfh | 7e0adcf | 2013-12-02 15:21:38 +0000 | [diff] [blame] | 66 | static cl::opt<std::string> |
| 67 | FallbackStyle("fallback-style", |
| 68 | cl::desc("The name of the predefined style used as a fallback in " |
| 69 | "case clang-format is invoked with -style=file, but can " |
| 70 | "not find the .clang-format file to use."), |
| 71 | cl::init("LLVM"), cl::cat(ClangFormatCategory)); |
djasper | 0584828 | 2013-09-13 13:40:24 +0000 | [diff] [blame] | 72 | |
| 73 | static cl::opt<std::string> |
| 74 | AssumeFilename("assume-filename", |
| 75 | cl::desc("When reading from stdin, clang-format assumes this\n" |
| 76 | "filename to look for a style config file (with\n" |
| 77 | "-style=file)."), |
| 78 | cl::cat(ClangFormatCategory)); |
| 79 | |
alexfh | 725a9f7 | 2013-05-10 18:12:00 +0000 | [diff] [blame] | 80 | static cl::opt<bool> Inplace("i", |
| 81 | cl::desc("Inplace edit <file>s, if specified."), |
| 82 | cl::cat(ClangFormatCategory)); |
| 83 | |
| 84 | static cl::opt<bool> OutputXML("output-replacements-xml", |
| 85 | cl::desc("Output replacements as XML."), |
| 86 | cl::cat(ClangFormatCategory)); |
alexfh | 5988345 | 2013-05-10 11:56:10 +0000 | [diff] [blame] | 87 | static cl::opt<bool> |
| 88 | DumpConfig("dump-config", |
alexfh | 725a9f7 | 2013-05-10 18:12:00 +0000 | [diff] [blame] | 89 | cl::desc("Dump configuration options to stdout and exit.\n" |
| 90 | "Can be used with -style option."), |
| 91 | cl::cat(ClangFormatCategory)); |
djasper | d0252b7 | 2013-05-21 12:21:39 +0000 | [diff] [blame] | 92 | static cl::opt<unsigned> |
| 93 | Cursor("cursor", |
alexfh | b5b4302 | 2013-09-02 15:30:26 +0000 | [diff] [blame] | 94 | cl::desc("The position of the cursor when invoking\n" |
| 95 | "clang-format from an editor integration"), |
djasper | d0252b7 | 2013-05-21 12:21:39 +0000 | [diff] [blame] | 96 | cl::init(0), cl::cat(ClangFormatCategory)); |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 97 | |
alexfh | 725a9f7 | 2013-05-10 18:12:00 +0000 | [diff] [blame] | 98 | static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"), |
| 99 | cl::cat(ClangFormatCategory)); |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 100 | |
| 101 | namespace clang { |
| 102 | namespace format { |
| 103 | |
| 104 | static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source, |
| 105 | SourceManager &Sources, FileManager &Files) { |
| 106 | const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" : |
| 107 | FileName, |
| 108 | Source->getBufferSize(), 0); |
| 109 | Sources.overrideFileContents(Entry, Source, true); |
| 110 | return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User); |
| 111 | } |
| 112 | |
alexfh | 6e70179 | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 113 | // Parses <start line>:<end line> input to a pair of line numbers. |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 114 | // Returns true on error. |
alexfh | 6e70179 | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 115 | static bool parseLineRange(StringRef Input, unsigned &FromLine, |
| 116 | unsigned &ToLine) { |
| 117 | std::pair<StringRef, StringRef> LineRange = Input.split(':'); |
| 118 | return LineRange.first.getAsInteger(0, FromLine) || |
| 119 | LineRange.second.getAsInteger(0, ToLine); |
| 120 | } |
| 121 | |
| 122 | static bool fillRanges(SourceManager &Sources, FileID ID, |
| 123 | const MemoryBuffer *Code, |
| 124 | std::vector<CharSourceRange> &Ranges) { |
| 125 | if (!LineRanges.empty()) { |
| 126 | if (!Offsets.empty() || !Lengths.empty()) { |
| 127 | llvm::errs() << "error: cannot use -lines with -offset/-length\n"; |
| 128 | return true; |
| 129 | } |
| 130 | |
| 131 | for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) { |
| 132 | unsigned FromLine, ToLine; |
| 133 | if (parseLineRange(LineRanges[i], FromLine, ToLine)) { |
| 134 | llvm::errs() << "error: invalid <start line>:<end line> pair\n"; |
| 135 | return true; |
| 136 | } |
| 137 | if (FromLine > ToLine) { |
| 138 | llvm::errs() << "error: start line should be less than end line\n"; |
| 139 | return true; |
| 140 | } |
| 141 | SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1); |
| 142 | SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX); |
| 143 | if (Start.isInvalid() || End.isInvalid()) |
| 144 | return true; |
| 145 | Ranges.push_back(CharSourceRange::getCharRange(Start, End)); |
| 146 | } |
| 147 | return false; |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 148 | } |
alexfh | 6e70179 | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 149 | |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 150 | if (Offsets.empty()) |
| 151 | Offsets.push_back(0); |
| 152 | if (Offsets.size() != Lengths.size() && |
| 153 | !(Offsets.size() == 1 && Lengths.empty())) { |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 154 | llvm::errs() |
| 155 | << "error: number of -offset and -length arguments must match.\n"; |
| 156 | return true; |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 157 | } |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 158 | for (unsigned i = 0, e = Offsets.size(); i != e; ++i) { |
| 159 | if (Offsets[i] >= Code->getBufferSize()) { |
| 160 | llvm::errs() << "error: offset " << Offsets[i] |
| 161 | << " is outside the file\n"; |
| 162 | return true; |
| 163 | } |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 164 | SourceLocation Start = |
| 165 | Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]); |
| 166 | SourceLocation End; |
| 167 | if (i < Lengths.size()) { |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 168 | if (Offsets[i] + Lengths[i] > Code->getBufferSize()) { |
| 169 | llvm::errs() << "error: invalid length " << Lengths[i] |
| 170 | << ", offset + length (" << Offsets[i] + Lengths[i] |
| 171 | << ") is outside the file.\n"; |
| 172 | return true; |
| 173 | } |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 174 | End = Start.getLocWithOffset(Lengths[i]); |
| 175 | } else { |
| 176 | End = Sources.getLocForEndOfFile(ID); |
| 177 | } |
| 178 | Ranges.push_back(CharSourceRange::getCharRange(Start, End)); |
| 179 | } |
alexfh | 6e70179 | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 180 | return false; |
| 181 | } |
| 182 | |
klimek | 82392d7 | 2013-12-03 09:46:06 +0000 | [diff] [blame] | 183 | static void outputReplacementXML(StringRef Text) { |
| 184 | size_t From = 0; |
| 185 | size_t Index; |
| 186 | while ((Index = Text.find_first_of("\n\r", From)) != StringRef::npos) { |
| 187 | llvm::outs() << Text.substr(From, Index - From); |
| 188 | switch (Text[Index]) { |
| 189 | case '\n': |
| 190 | llvm::outs() << " "; |
| 191 | break; |
| 192 | case '\r': |
| 193 | llvm::outs() << " "; |
| 194 | break; |
| 195 | default: |
| 196 | llvm_unreachable("Unexpected character encountered!"); |
| 197 | } |
| 198 | From = Index + 1; |
| 199 | } |
| 200 | llvm::outs() << Text.substr(From); |
| 201 | } |
| 202 | |
alexfh | 6e70179 | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 203 | // Returns true on error. |
void | a14558f | 2013-11-09 00:23:58 +0000 | [diff] [blame] | 204 | static bool format(StringRef FileName) { |
alexfh | 6e70179 | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 205 | FileManager Files((FileSystemOptions())); |
| 206 | DiagnosticsEngine Diagnostics( |
| 207 | IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), |
| 208 | new DiagnosticOptions); |
| 209 | SourceManager Sources(Diagnostics, Files); |
| 210 | OwningPtr<MemoryBuffer> Code; |
| 211 | if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) { |
| 212 | llvm::errs() << ec.message() << "\n"; |
| 213 | return true; |
| 214 | } |
| 215 | if (Code->getBufferSize() == 0) |
djasper | 60dad2e | 2013-10-08 15:54:36 +0000 | [diff] [blame] | 216 | return false; // Empty files are formatted correctly. |
alexfh | 6e70179 | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 217 | FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files); |
| 218 | std::vector<CharSourceRange> Ranges; |
| 219 | if (fillRanges(Sources, ID, Code.get(), Ranges)) |
| 220 | return true; |
| 221 | |
alexfh | 7e0adcf | 2013-12-02 15:21:38 +0000 | [diff] [blame] | 222 | FormatStyle FormatStyle = getStyle( |
| 223 | Style, (FileName == "-") ? AssumeFilename : FileName, FallbackStyle); |
alexfh | 943428e | 2013-06-28 12:51:24 +0000 | [diff] [blame] | 224 | Lexer Lex(ID, Sources.getBuffer(ID), Sources, |
| 225 | getFormattingLangOpts(FormatStyle.Standard)); |
| 226 | tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges); |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 227 | if (OutputXML) { |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 228 | llvm::outs() |
| 229 | << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n"; |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 230 | for (tooling::Replacements::const_iterator I = Replaces.begin(), |
| 231 | E = Replaces.end(); |
| 232 | I != E; ++I) { |
| 233 | llvm::outs() << "<replacement " |
| 234 | << "offset='" << I->getOffset() << "' " |
klimek | 82392d7 | 2013-12-03 09:46:06 +0000 | [diff] [blame] | 235 | << "length='" << I->getLength() << "'>"; |
| 236 | outputReplacementXML(I->getReplacementText()); |
| 237 | llvm::outs() << "</replacement>\n"; |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 238 | } |
| 239 | llvm::outs() << "</replacements>\n"; |
| 240 | } else { |
| 241 | Rewriter Rewrite(Sources, LangOptions()); |
| 242 | tooling::applyAllReplacements(Replaces, Rewrite); |
| 243 | if (Inplace) { |
alp | 8d1b4dd | 2013-11-08 08:07:19 +0000 | [diff] [blame] | 244 | if (Rewrite.overwriteChangedFiles()) |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 245 | return true; |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 246 | } else { |
djasper | 898b4f7 | 2013-05-21 14:21:46 +0000 | [diff] [blame] | 247 | if (Cursor.getNumOccurrences() != 0) |
djasper | d0252b7 | 2013-05-21 12:21:39 +0000 | [diff] [blame] | 248 | outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition( |
| 249 | Replaces, Cursor) << " }\n"; |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 250 | Rewrite.getEditBuffer(ID).write(outs()); |
| 251 | } |
| 252 | } |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 253 | return false; |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 254 | } |
| 255 | |
| 256 | } // namespace format |
| 257 | } // namespace clang |
| 258 | |
nico | 436d02f | 2014-01-07 16:27:35 +0000 | [diff] [blame] | 259 | static void PrintVersion() { |
| 260 | raw_ostream &OS = outs(); |
| 261 | OS << clang::getClangToolFullVersion("clang-format") << '\n'; |
| 262 | } |
| 263 | |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 264 | int main(int argc, const char **argv) { |
| 265 | llvm::sys::PrintStackTraceOnErrorSignal(); |
alexfh | 725a9f7 | 2013-05-10 18:12:00 +0000 | [diff] [blame] | 266 | |
| 267 | // Hide unrelated options. |
| 268 | StringMap<cl::Option*> Options; |
| 269 | cl::getRegisteredOptions(Options); |
| 270 | for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end(); |
| 271 | I != E; ++I) { |
| 272 | if (I->second->Category != &ClangFormatCategory && I->first() != "help" && |
| 273 | I->first() != "version") |
| 274 | I->second->setHiddenFlag(cl::ReallyHidden); |
| 275 | } |
| 276 | |
nico | 436d02f | 2014-01-07 16:27:35 +0000 | [diff] [blame] | 277 | cl::SetVersionPrinter(PrintVersion); |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 278 | cl::ParseCommandLineOptions( |
| 279 | argc, argv, |
| 280 | "A tool to format C/C++/Obj-C code.\n\n" |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 281 | "If no arguments are specified, it formats the code from standard input\n" |
| 282 | "and writes the result to the standard output.\n" |
alexfh | b5b4302 | 2013-09-02 15:30:26 +0000 | [diff] [blame] | 283 | "If <file>s are given, it reformats the files. If -i is specified\n" |
| 284 | "together with <file>s, the files are edited in-place. Otherwise, the\n" |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 285 | "result is written to the standard output.\n"); |
| 286 | |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 287 | if (Help) |
| 288 | cl::PrintHelpMessage(); |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 289 | |
alexfh | 5988345 | 2013-05-10 11:56:10 +0000 | [diff] [blame] | 290 | if (DumpConfig) { |
revane | 4d11869 | 2013-09-30 13:31:48 +0000 | [diff] [blame] | 291 | std::string Config = |
| 292 | clang::format::configurationAsText(clang::format::getStyle( |
alexfh | 7e0adcf | 2013-12-02 15:21:38 +0000 | [diff] [blame] | 293 | Style, FileNames.empty() ? AssumeFilename : FileNames[0], |
| 294 | FallbackStyle)); |
alexfh | 5988345 | 2013-05-10 11:56:10 +0000 | [diff] [blame] | 295 | llvm::outs() << Config << "\n"; |
| 296 | return 0; |
| 297 | } |
| 298 | |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 299 | bool Error = false; |
| 300 | switch (FileNames.size()) { |
| 301 | case 0: |
| 302 | Error = clang::format::format("-"); |
| 303 | break; |
| 304 | case 1: |
| 305 | Error = clang::format::format(FileNames[0]); |
| 306 | break; |
| 307 | default: |
alexfh | 6e70179 | 2013-07-18 22:54:56 +0000 | [diff] [blame] | 308 | if (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty()) { |
| 309 | llvm::errs() << "error: -offset, -length and -lines can only be used for " |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 310 | "single file.\n"; |
| 311 | return 1; |
| 312 | } |
| 313 | for (unsigned i = 0; i < FileNames.size(); ++i) |
| 314 | Error |= clang::format::format(FileNames[i]); |
| 315 | break; |
| 316 | } |
| 317 | return Error ? 1 : 0; |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 318 | } |