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" |
| 20 | #include "clang/Format/Format.h" |
| 21 | #include "clang/Lex/Lexer.h" |
| 22 | #include "clang/Rewrite/Core/Rewriter.h" |
alexfh | 5988345 | 2013-05-10 11:56:10 +0000 | [diff] [blame^] | 23 | #include "llvm/Support/Debug.h" |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 24 | #include "llvm/Support/FileSystem.h" |
| 25 | #include "llvm/Support/Signals.h" |
| 26 | |
| 27 | using namespace llvm; |
| 28 | |
| 29 | static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden); |
| 30 | |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 31 | static cl::list<unsigned> |
| 32 | Offsets("offset", cl::desc("Format a range starting at this file offset. Can " |
| 33 | "only be used with one input file.")); |
| 34 | static cl::list<unsigned> |
| 35 | Lengths("length", cl::desc("Format a range of this length. " |
| 36 | "When it's not specified, end of file is used. " |
| 37 | "Can only be used with one input file.")); |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 38 | static cl::opt<std::string> Style( |
| 39 | "style", |
alexfh | 5988345 | 2013-05-10 11:56:10 +0000 | [diff] [blame^] | 40 | cl::desc( |
| 41 | "Coding style, currently supports: LLVM, Google, Chromium, Mozilla. " |
| 42 | "Use '-style file' to load style configuration from .clang-format file " |
| 43 | "located in one of the parent directories of the source file (or " |
| 44 | "current directory for stdin)."), |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 45 | cl::init("LLVM")); |
| 46 | static cl::opt<bool> Inplace("i", |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 47 | cl::desc("Inplace edit <file>s, if specified.")); |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 48 | |
| 49 | static cl::opt<bool> OutputXML( |
| 50 | "output-replacements-xml", cl::desc("Output replacements as XML.")); |
alexfh | 5988345 | 2013-05-10 11:56:10 +0000 | [diff] [blame^] | 51 | static cl::opt<bool> |
| 52 | DumpConfig("dump-config", |
| 53 | cl::desc("Dump configuration options to stdout and exit. Can be used with -style option.")); |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 54 | |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 55 | static cl::list<std::string> FileNames(cl::Positional, |
| 56 | cl::desc("[<file> ...]")); |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 57 | |
| 58 | namespace clang { |
| 59 | namespace format { |
| 60 | |
| 61 | static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source, |
| 62 | SourceManager &Sources, FileManager &Files) { |
| 63 | const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" : |
| 64 | FileName, |
| 65 | Source->getBufferSize(), 0); |
| 66 | Sources.overrideFileContents(Entry, Source, true); |
| 67 | return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User); |
| 68 | } |
| 69 | |
alexfh | 5988345 | 2013-05-10 11:56:10 +0000 | [diff] [blame^] | 70 | FormatStyle getStyle(StringRef StyleName, StringRef FileName) { |
| 71 | if (!StyleName.equals_lower("file")) |
| 72 | return getPredefinedStyle(StyleName); |
alexfh | 2d77617 | 2013-05-06 14:11:27 +0000 | [diff] [blame] | 73 | |
alexfh | 5988345 | 2013-05-10 11:56:10 +0000 | [diff] [blame^] | 74 | SmallString<128> Path(FileName); |
| 75 | llvm::sys::fs::make_absolute(Path); |
| 76 | for (StringRef Directory = llvm::sys::path::parent_path(Path); |
| 77 | !Directory.empty(); |
| 78 | Directory = llvm::sys::path::parent_path(Directory)) { |
| 79 | SmallString<128> ConfigFile(Directory); |
| 80 | llvm::sys::path::append(ConfigFile, ".clang-format"); |
| 81 | DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n"); |
| 82 | bool IsFile = false; |
| 83 | llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile); |
| 84 | if (IsFile) { |
| 85 | OwningPtr<MemoryBuffer> Text; |
| 86 | if (error_code ec = MemoryBuffer::getFile(ConfigFile, Text)) { |
| 87 | llvm::errs() << ec.message() << "\n"; |
| 88 | continue; |
| 89 | } |
| 90 | FormatStyle Style; |
| 91 | if (error_code ec = parseConfiguration(Text->getBuffer(), &Style)) { |
| 92 | llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message() |
| 93 | << "\n"; |
| 94 | continue; |
| 95 | } |
| 96 | DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n"); |
| 97 | return Style; |
| 98 | } |
| 99 | } |
| 100 | llvm::errs() << "Can't find usable .clang-format, using LLVM style\n"; |
| 101 | return getLLVMStyle(); |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 102 | } |
| 103 | |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 104 | // Returns true on error. |
| 105 | static bool format(std::string FileName) { |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 106 | FileManager Files((FileSystemOptions())); |
| 107 | DiagnosticsEngine Diagnostics( |
| 108 | IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), |
| 109 | new DiagnosticOptions); |
| 110 | SourceManager Sources(Diagnostics, Files); |
| 111 | OwningPtr<MemoryBuffer> Code; |
| 112 | if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) { |
| 113 | llvm::errs() << ec.message() << "\n"; |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 114 | return true; |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 115 | } |
| 116 | FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files); |
| 117 | Lexer Lex(ID, Sources.getBuffer(ID), Sources, getFormattingLangOpts()); |
| 118 | if (Offsets.empty()) |
| 119 | Offsets.push_back(0); |
| 120 | if (Offsets.size() != Lengths.size() && |
| 121 | !(Offsets.size() == 1 && Lengths.empty())) { |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 122 | llvm::errs() |
| 123 | << "error: number of -offset and -length arguments must match.\n"; |
| 124 | return true; |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 125 | } |
| 126 | std::vector<CharSourceRange> Ranges; |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 127 | for (unsigned i = 0, e = Offsets.size(); i != e; ++i) { |
| 128 | if (Offsets[i] >= Code->getBufferSize()) { |
| 129 | llvm::errs() << "error: offset " << Offsets[i] |
| 130 | << " is outside the file\n"; |
| 131 | return true; |
| 132 | } |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 133 | SourceLocation Start = |
| 134 | Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]); |
| 135 | SourceLocation End; |
| 136 | if (i < Lengths.size()) { |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 137 | if (Offsets[i] + Lengths[i] > Code->getBufferSize()) { |
| 138 | llvm::errs() << "error: invalid length " << Lengths[i] |
| 139 | << ", offset + length (" << Offsets[i] + Lengths[i] |
| 140 | << ") is outside the file.\n"; |
| 141 | return true; |
| 142 | } |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 143 | End = Start.getLocWithOffset(Lengths[i]); |
| 144 | } else { |
| 145 | End = Sources.getLocForEndOfFile(ID); |
| 146 | } |
| 147 | Ranges.push_back(CharSourceRange::getCharRange(Start, End)); |
| 148 | } |
alexfh | 5988345 | 2013-05-10 11:56:10 +0000 | [diff] [blame^] | 149 | tooling::Replacements Replaces = |
| 150 | reformat(getStyle(Style, FileName), Lex, Sources, Ranges); |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 151 | if (OutputXML) { |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 152 | llvm::outs() |
| 153 | << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n"; |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 154 | for (tooling::Replacements::const_iterator I = Replaces.begin(), |
| 155 | E = Replaces.end(); |
| 156 | I != E; ++I) { |
| 157 | llvm::outs() << "<replacement " |
| 158 | << "offset='" << I->getOffset() << "' " |
| 159 | << "length='" << I->getLength() << "'>" |
| 160 | << I->getReplacementText() << "</replacement>\n"; |
| 161 | } |
| 162 | llvm::outs() << "</replacements>\n"; |
| 163 | } else { |
| 164 | Rewriter Rewrite(Sources, LangOptions()); |
| 165 | tooling::applyAllReplacements(Replaces, Rewrite); |
| 166 | if (Inplace) { |
| 167 | if (Replaces.size() == 0) |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 168 | return false; // Nothing changed, don't touch the file. |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 169 | |
| 170 | std::string ErrorInfo; |
| 171 | llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo, |
| 172 | llvm::raw_fd_ostream::F_Binary); |
| 173 | if (!ErrorInfo.empty()) { |
| 174 | llvm::errs() << "Error while writing file: " << ErrorInfo << "\n"; |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 175 | return true; |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 176 | } |
| 177 | Rewrite.getEditBuffer(ID).write(FileStream); |
| 178 | FileStream.flush(); |
| 179 | } else { |
| 180 | Rewrite.getEditBuffer(ID).write(outs()); |
| 181 | } |
| 182 | } |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 183 | return false; |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 184 | } |
| 185 | |
| 186 | } // namespace format |
| 187 | } // namespace clang |
| 188 | |
| 189 | int main(int argc, const char **argv) { |
| 190 | llvm::sys::PrintStackTraceOnErrorSignal(); |
| 191 | cl::ParseCommandLineOptions( |
| 192 | argc, argv, |
| 193 | "A tool to format C/C++/Obj-C code.\n\n" |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 194 | "If no arguments are specified, it formats the code from standard input\n" |
| 195 | "and writes the result to the standard output.\n" |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 196 | "If <file>s are given, it reformats the files. If -i is specified \n" |
| 197 | "together with <file>s, the files are edited in-place. Otherwise, the \n" |
| 198 | "result is written to the standard output.\n"); |
| 199 | |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 200 | if (Help) |
| 201 | cl::PrintHelpMessage(); |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 202 | |
alexfh | 5988345 | 2013-05-10 11:56:10 +0000 | [diff] [blame^] | 203 | if (DumpConfig) { |
| 204 | std::string Config = clang::format::configurationAsText( |
| 205 | clang::format::getStyle(Style, FileNames.empty() ? "-" : FileNames[0])); |
| 206 | llvm::outs() << Config << "\n"; |
| 207 | return 0; |
| 208 | } |
| 209 | |
alexfh | 4df4364 | 2013-04-24 12:46:44 +0000 | [diff] [blame] | 210 | bool Error = false; |
| 211 | switch (FileNames.size()) { |
| 212 | case 0: |
| 213 | Error = clang::format::format("-"); |
| 214 | break; |
| 215 | case 1: |
| 216 | Error = clang::format::format(FileNames[0]); |
| 217 | break; |
| 218 | default: |
| 219 | if (!Offsets.empty() || !Lengths.empty()) { |
| 220 | llvm::errs() << "error: \"-offset\" and \"-length\" can only be used for " |
| 221 | "single file.\n"; |
| 222 | return 1; |
| 223 | } |
| 224 | for (unsigned i = 0; i < FileNames.size(); ++i) |
| 225 | Error |= clang::format::format(FileNames[i]); |
| 226 | break; |
| 227 | } |
| 228 | return Error ? 1 : 0; |
djasper | 7f66360 | 2013-03-20 09:53:23 +0000 | [diff] [blame] | 229 | } |