clang-tools 10.0.0

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