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