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/Format/Format.h" 21 #include "clang/Lex/Lexer.h" 22 #include "clang/Rewrite/Core/Rewriter.h" 23 #include "llvm/Support/FileSystem.h" 24 #include "llvm/Support/Signals.h" 25 26 using namespace llvm; 27 28 static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden); 29 30 static cl::list<unsigned> 31 Offsets("offset", cl::desc("Format a range starting at this file offset. Can " 32 "only be used with one input file.")); 33 static cl::list<unsigned> 34 Lengths("length", cl::desc("Format a range of this length. " 35 "When it's not specified, end of file is used. " 36 "Can only be used with one input file.")); 37 static cl::opt<std::string> Style( 38 "style", 39 cl::desc("Coding style, currently supports: LLVM, Google, Chromium."), 40 cl::init("LLVM")); 41 static cl::opt<bool> Inplace("i", 42 cl::desc("Inplace edit <file>s, if specified.")); 43 44 static cl::opt<bool> OutputXML( 45 "output-replacements-xml", cl::desc("Output replacements as XML.")); 46 47 static cl::list<std::string> FileNames(cl::Positional, 48 cl::desc("[<file> ...]")); 49 50 namespace clang { 51 namespace format { 52 53 static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source, 54 SourceManager &Sources, FileManager &Files) { 55 const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" : 56 FileName, 57 Source->getBufferSize(), 0); 58 Sources.overrideFileContents(Entry, Source, true); 59 return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User); 60 } 61 62 static FormatStyle getStyle() { 63 FormatStyle TheStyle = getGoogleStyle(); 64 if (Style == "LLVM") 65 TheStyle = getLLVMStyle(); 66 if (Style == "Chromium") 67 TheStyle = getChromiumStyle(); 68 return TheStyle; 69 } 70 71 // Returns true on error. 72 static bool format(std::string FileName) { 73 FileManager Files((FileSystemOptions())); 74 DiagnosticsEngine Diagnostics( 75 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), 76 new DiagnosticOptions); 77 SourceManager Sources(Diagnostics, Files); 78 OwningPtr<MemoryBuffer> Code; 79 if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) { 80 llvm::errs() << ec.message() << "\n"; 81 return true; 82 } 83 FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files); 84 Lexer Lex(ID, Sources.getBuffer(ID), Sources, getFormattingLangOpts()); 85 if (Offsets.empty()) 86 Offsets.push_back(0); 87 if (Offsets.size() != Lengths.size() && 88 !(Offsets.size() == 1 && Lengths.empty())) { 89 llvm::errs() 90 << "error: number of -offset and -length arguments must match.\n"; 91 return true; 92 } 93 std::vector<CharSourceRange> Ranges; 94 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) { 95 if (Offsets[i] >= Code->getBufferSize()) { 96 llvm::errs() << "error: offset " << Offsets[i] 97 << " is outside the file\n"; 98 return true; 99 } 100 SourceLocation Start = 101 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]); 102 SourceLocation End; 103 if (i < Lengths.size()) { 104 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) { 105 llvm::errs() << "error: invalid length " << Lengths[i] 106 << ", offset + length (" << Offsets[i] + Lengths[i] 107 << ") is outside the file.\n"; 108 return true; 109 } 110 End = Start.getLocWithOffset(Lengths[i]); 111 } else { 112 End = Sources.getLocForEndOfFile(ID); 113 } 114 Ranges.push_back(CharSourceRange::getCharRange(Start, End)); 115 } 116 tooling::Replacements Replaces = reformat(getStyle(), Lex, Sources, Ranges); 117 if (OutputXML) { 118 llvm::outs() 119 << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n"; 120 for (tooling::Replacements::const_iterator I = Replaces.begin(), 121 E = Replaces.end(); 122 I != E; ++I) { 123 llvm::outs() << "<replacement " 124 << "offset='" << I->getOffset() << "' " 125 << "length='" << I->getLength() << "'>" 126 << I->getReplacementText() << "</replacement>\n"; 127 } 128 llvm::outs() << "</replacements>\n"; 129 } else { 130 Rewriter Rewrite(Sources, LangOptions()); 131 tooling::applyAllReplacements(Replaces, Rewrite); 132 if (Inplace) { 133 if (Replaces.size() == 0) 134 return false; // Nothing changed, don't touch the file. 135 136 std::string ErrorInfo; 137 llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo, 138 llvm::raw_fd_ostream::F_Binary); 139 if (!ErrorInfo.empty()) { 140 llvm::errs() << "Error while writing file: " << ErrorInfo << "\n"; 141 return true; 142 } 143 Rewrite.getEditBuffer(ID).write(FileStream); 144 FileStream.flush(); 145 } else { 146 Rewrite.getEditBuffer(ID).write(outs()); 147 } 148 } 149 return false; 150 } 151 152 } // namespace format 153 } // namespace clang 154 155 int main(int argc, const char **argv) { 156 llvm::sys::PrintStackTraceOnErrorSignal(); 157 cl::ParseCommandLineOptions( 158 argc, argv, 159 "A tool to format C/C++/Obj-C code.\n\n" 160 "If no arguments are specified, it formats the code from standard input\n" 161 "and writes the result to the standard output.\n" 162 "If <file>s are given, it reformats the files. If -i is specified \n" 163 "together with <file>s, the files are edited in-place. Otherwise, the \n" 164 "result is written to the standard output.\n"); 165 166 if (Help) 167 cl::PrintHelpMessage(); 168 169 bool Error = false; 170 switch (FileNames.size()) { 171 case 0: 172 Error = clang::format::format("-"); 173 break; 174 case 1: 175 Error = clang::format::format(FileNames[0]); 176 break; 177 default: 178 if (!Offsets.empty() || !Lengths.empty()) { 179 llvm::errs() << "error: \"-offset\" and \"-length\" can only be used for " 180 "single file.\n"; 181 return 1; 182 } 183 for (unsigned i = 0; i < FileNames.size(); ++i) 184 Error |= clang::format::format(FileNames[i]); 185 break; 186 } 187 return Error ? 1 : 0; 188 } 189