clang-tools 8.0.0

ClangApplyReplacementsMain.cpp
Go to the documentation of this file.
1 //===-- ClangApplyReplacementsMain.cpp - Main file for the 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 provides the main function for the
12 /// clang-apply-replacements tool.
13 ///
14 //===----------------------------------------------------------------------===//
15
16 #include "clang-apply-replacements/Tooling/ApplyReplacements.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/DiagnosticOptions.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Basic/Version.h"
21 #include "clang/Format/Format.h"
22 #include "clang/Rewrite/Core/Rewriter.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/StringSet.h"
25 #include "llvm/Support/CommandLine.h"
26
27 using namespace llvm;
28 using namespace clang;
29 using namespace clang::replace;
30
31 static cl::opt<std::string> Directory(cl::Positional, cl::Required,
32 cl::desc("<Search Root Directory>"));
33
34 static cl::OptionCategory ReplacementCategory("Replacement Options");
35 static cl::OptionCategory FormattingCategory("Formatting Options");
36
37 const cl::OptionCategory *VisibleCategories[] = {&ReplacementCategory,
38 &FormattingCategory};
39
40 static cl::opt<bool> RemoveTUReplacementFiles(
41 "remove-change-desc-files",
42 cl::desc("Remove the change description files regardless of successful\n"
43 "merging/replacing."),
44 cl::init(false), cl::cat(ReplacementCategory));
45
46 static cl::opt<bool> DoFormat(
47 "format",
48 cl::desc("Enable formatting of code changed by applying replacements.\n"
49 "Use -style to choose formatting style.\n"),
50 cl::cat(FormattingCategory));
51
52 // FIXME: Consider making the default behaviour for finding a style
53 // configuration file to start the search anew for every file being changed to
54 // handle situations where the style is different for different parts of a
55 // project.
56
57 static cl::opt<std::string> FormatStyleConfig(
58 "style-config",
59 cl::desc("Path to a directory containing a .clang-format file\n"
60 "describing a formatting style to use for formatting\n"
61 "code when -style=file.\n"),
62 cl::init(""), cl::cat(FormattingCategory));
63
64 static cl::opt<std::string>
65 FormatStyleOpt("style", cl::desc(format::StyleOptionHelpDescription),
66 cl::init("LLVM"), cl::cat(FormattingCategory));
67
68 namespace {
69 // Helper object to remove the TUReplacement and TUDiagnostic (triggered by
70 // "remove-change-desc-files" command line option) when exiting current scope.
71 class ScopedFileRemover {
72 public:
73 ScopedFileRemover(const TUReplacementFiles &Files,
74 clang::DiagnosticsEngine &Diagnostics)
75 : TURFiles(Files), Diag(Diagnostics) {}
76
77 ~ScopedFileRemover() { deleteReplacementFiles(TURFiles, Diag); }
78
79 private:
80 const TUReplacementFiles &TURFiles;
81 clang::DiagnosticsEngine &Diag;
82 };
83 } // namespace
84
85 static void printVersion(raw_ostream &OS) {
86 OS << "clang-apply-replacements version " CLANG_VERSION_STRING << "\n";
87 }
88
89 int main(int argc, char **argv) {
90 cl::HideUnrelatedOptions(makeArrayRef(VisibleCategories));
91
92 cl::SetVersionPrinter(printVersion);
93 cl::ParseCommandLineOptions(argc, argv);
94
95 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions());
96 DiagnosticsEngine Diagnostics(
97 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), DiagOpts.get());
98
99 // Determine a formatting style from options.
100 auto FormatStyleOrError = format::getStyle(FormatStyleOpt, FormatStyleConfig,
101 format::DefaultFallbackStyle);
102 if (!FormatStyleOrError) {
103 llvm::errs() << llvm::toString(FormatStyleOrError.takeError()) << "\n";
104 return 1;
105 }
106 format::FormatStyle FormatStyle = std::move(*FormatStyleOrError);
107
108 TUReplacements TURs;
109 TUReplacementFiles TUFiles;
110
111 std::error_code ErrorCode =
112 collectReplacementsFromDirectory(Directory, TURs, TUFiles, Diagnostics);
113
114 TUDiagnostics TUDs;
115 TUFiles.clear();
116 ErrorCode =
117 collectReplacementsFromDirectory(Directory, TUDs, TUFiles, Diagnostics);
118
119 if (ErrorCode) {
120 errs() << "Trouble iterating over directory '" << Directory
121 << "': " << ErrorCode.message() << "\n";
122 return 1;
123 }
124
125 // Remove the TUReplacementFiles (triggered by "remove-change-desc-files"
126 // command line option) when exiting main().
127 std::unique_ptr<ScopedFileRemover> Remover;
128 if (RemoveTUReplacementFiles)
129 Remover.reset(new ScopedFileRemover(TUFiles, Diagnostics));
130
131 FileManager Files((FileSystemOptions()));
132 SourceManager SM(Diagnostics, Files);
133
134 FileToChangesMap Changes;
135 if (!mergeAndDeduplicate(TURs, TUDs, Changes, SM))
136 return 1;
137
138 tooling::ApplyChangesSpec Spec;
139 Spec.Cleanup = true;
140 Spec.Style = FormatStyle;
141 Spec.Format = DoFormat ? tooling::ApplyChangesSpec::kAll
142 : tooling::ApplyChangesSpec::kNone;
143
144 for (const auto &FileChange : Changes) {
145 const FileEntry *Entry = FileChange.first;
146 StringRef FileName = Entry->getName();
147 llvm::Expected<std::string> NewFileData =
148 applyChanges(FileName, FileChange.second, Spec, Diagnostics);
149 if (!NewFileData) {
150 errs() << llvm::toString(NewFileData.takeError()) << "\n";
151 continue;
152 }
153
154 // Write new file to disk
155 std::error_code EC;
156 llvm::raw_fd_ostream FileStream(FileName, EC, llvm::sys::fs::F_None);
157 if (EC) {
158 llvm::errs() << "Could not open " << FileName << " for writing\n";
159 continue;
160 }
161 FileStream << *NewFileData;
162 }
163
164 return 0;
165 }
llvm
Some operations such as code completion produce a set of candidates.
Definition: YAMLGenerator.cpp:28
clang::replace::deleteReplacementFiles
bool deleteReplacementFiles(const TUReplacementFiles &Files, clang::DiagnosticsEngine &Diagnostics)
Delete the replacement files.
Definition: ApplyReplacements.cpp:243
FormattingCategory
static cl::OptionCategory FormattingCategory("Formatting Options")
clang::replace::TUReplacements
std::vector< clang::tooling::TranslationUnitReplacements > TUReplacements
Collection of TranslationUnitReplacements.
Definition: ApplyReplacements.h:36
clang::tidy::cppcoreguidelines::toString
static llvm::StringRef toString(SpecialMemberFunctionsCheck::SpecialMemberFunctionKind K)
Definition: SpecialMemberFunctionsCheck.cpp:59
RemoveTUReplacementFiles
static cl::opt< bool > RemoveTUReplacementFiles("remove-change-desc-files", cl::desc("Remove the change description files regardless of successful\ "merging/replacing."), cl::init(false), cl::cat(ReplacementCategory))
Directory
static cl::opt< std::string > Directory(cl::Positional, cl::Required, cl::desc("<Search Root Directory>"))
printVersion
static void printVersion(raw_ostream &OS)
Definition: ClangApplyReplacementsMain.cpp:85
clang::clangd::ErrorCode
ErrorCode
Definition: Protocol.h:38
clang::replace::applyChanges
llvm::Expected< std::string > applyChanges(StringRef File, const std::vector< tooling::AtomicChange > &Changes, const tooling::ApplyChangesSpec &Spec, DiagnosticsEngine &Diagnostics)
Apply AtomicChange on File and rewrite it.
Definition: ApplyReplacements.cpp:229
ReplacementCategory
static cl::OptionCategory ReplacementCategory("Replacement Options")
FileName
PathRef FileName
Definition: CodeComplete.cpp:1004
FormatStyleOpt
static cl::opt< std::string > FormatStyleOpt("style", cl::desc(format::StyleOptionHelpDescription), cl::init("LLVM"), cl::cat(FormattingCategory))
DoFormat
static cl::opt< bool > DoFormat("format", cl::desc("Enable formatting of code changed by applying replacements.\ "Use -style to choose formatting style.\"), cl::cat(FormattingCategory))
clang::replace::collectReplacementsFromDirectory
std::error_code collectReplacementsFromDirectory(const llvm::StringRef Directory, TUReplacements &TUs, TUReplacementFiles &TUFiles, clang::DiagnosticsEngine &Diagnostics)
Recursively descends through a directory structure rooted at Directory and attempts to deserialize *...
Definition: ApplyReplacements.cpp:39
VisibleCategories
const cl::OptionCategory * VisibleCategories[]
Definition: ClangApplyReplacementsMain.cpp:37
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ChangeNamespace.cpp:18
clang::replace::mergeAndDeduplicate
bool mergeAndDeduplicate(const TUReplacements &TUs, const TUDiagnostics &TUDs, FileToChangesMap &FileChanges, clang::SourceManager &SM)
Deduplicate, check for conflicts, and extract all Replacements stored in TUs.
Definition: ApplyReplacements.cpp:187
main
int main(int argc, char **argv)
Definition: ClangApplyReplacementsMain.cpp:89
ApplyReplacements.h
This file provides the interface for deduplicating, detecting conflicts in, and applying collections ...
clang::replace::TUDiagnostics
std::vector< clang::tooling::TranslationUnitDiagnostics > TUDiagnostics
Collection of TranslationUniDiagnostics.
Definition: ApplyReplacements.h:42
FormatStyleConfig
static cl::opt< std::string > FormatStyleConfig("style-config", cl::desc("Path to a directory containing a .clang-format file\ "describing a formatting style to use for formatting\" "code when -style=file.\"), cl::init(""), cl::cat(FormattingCategory))
clang::replace::TUReplacementFiles
std::vector< std::string > TUReplacementFiles
Collection of TranslationUnitReplacement files.
Definition: ApplyReplacements.h:39
clang::replace::FileToChangesMap
llvm::DenseMap< const clang::FileEntry *, std::vector< tooling::AtomicChange > > FileToChangesMap
Map mapping file name to a set of AtomicChange targeting that file.
Definition: ApplyReplacements.h:47
clang::replace
Definition: ApplyReplacements.h:33
Entry
Definition: Modularize.cpp:430
FormatStyle
static cl::opt< std::string > FormatStyle("format-style", cl::desc(R"( Style for formatting code around applied fixes: - 'none' (default) turns off formatting - 'file' (literally 'file', not a placeholder) uses .clang-format file in the closest parent directory - '{ <json> }' specifies options inline, e.g. -format-style='{BasedOnStyle: llvm, IndentWidth: 8}' - 'llvm', 'google', 'webkit', 'mozilla' See clang-format documentation for the up-to-date information about formatting styles and options. This option overrides the 'FormatStyle` option in .clang-tidy file, if any. )"), cl::init("none"), cl::cat(ClangTidyCategory))