diff options
Diffstat (limited to 'contrib/llvm/tools/clang/lib/Tooling')
6 files changed, 156 insertions, 133 deletions
diff --git a/contrib/llvm/tools/clang/lib/Tooling/CommonOptionsParser.cpp b/contrib/llvm/tools/clang/lib/Tooling/CommonOptionsParser.cpp index cce4816..e0b844c 100644 --- a/contrib/llvm/tools/clang/lib/Tooling/CommonOptionsParser.cpp +++ b/contrib/llvm/tools/clang/lib/Tooling/CommonOptionsParser.cpp @@ -54,12 +54,26 @@ const char *const CommonOptionsParser::HelpMessage = "\n"; CommonOptionsParser::CommonOptionsParser(int &argc, const char **argv, + cl::OptionCategory &Category, const char *Overview) { - static cl::opt<std::string> BuildPath( - "p", cl::desc("Build path"), cl::Optional); + static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden); + + static cl::opt<std::string> BuildPath("p", cl::desc("Build path"), + cl::Optional, cl::cat(Category)); static cl::list<std::string> SourcePaths( - cl::Positional, cl::desc("<source0> [... <sourceN>]"), cl::OneOrMore); + cl::Positional, cl::desc("<source0> [... <sourceN>]"), cl::OneOrMore, + cl::cat(Category)); + + // Hide unrelated options. + StringMap<cl::Option*> Options; + cl::getRegisteredOptions(Options); + for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end(); + I != E; ++I) { + if (I->second->Category != &Category && I->first() != "help" && + I->first() != "version") + I->second->setHiddenFlag(cl::ReallyHidden); + } Compilations.reset(FixedCompilationDatabase::loadFromCommandLine(argc, argv)); diff --git a/contrib/llvm/tools/clang/lib/Tooling/CompilationDatabase.cpp b/contrib/llvm/tools/clang/lib/Tooling/CompilationDatabase.cpp index c962055..4b776bf 100644 --- a/contrib/llvm/tools/clang/lib/Tooling/CompilationDatabase.cpp +++ b/contrib/llvm/tools/clang/lib/Tooling/CompilationDatabase.cpp @@ -13,22 +13,22 @@ //===----------------------------------------------------------------------===// #include "clang/Tooling/CompilationDatabase.h" -#include "clang/Tooling/CompilationDatabasePluginRegistry.h" -#include "clang/Tooling/Tooling.h" -#include "llvm/ADT/SmallString.h" -#include "llvm/Support/Path.h" -#include "llvm/Support/system_error.h" -#include <sstream> - #include "clang/Basic/Diagnostic.h" +#include "clang/Basic/DiagnosticOptions.h" #include "clang/Driver/Action.h" +#include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Job.h" -#include "clang/Driver/Compilation.h" #include "clang/Frontend/TextDiagnosticPrinter.h" -#include "llvm/Support/Host.h" +#include "clang/Tooling/CompilationDatabasePluginRegistry.h" +#include "clang/Tooling/Tooling.h" +#include "llvm/ADT/SmallString.h" #include "llvm/Option/Arg.h" +#include "llvm/Support/Host.h" +#include "llvm/Support/Path.h" +#include <sstream> +#include <system_error> namespace clang { namespace tooling { @@ -44,7 +44,7 @@ CompilationDatabase::loadFromDirectory(StringRef BuildDirectory, Ie = CompilationDatabasePluginRegistry::end(); It != Ie; ++It) { std::string DatabaseErrorMessage; - OwningPtr<CompilationDatabasePlugin> Plugin(It->instantiate()); + std::unique_ptr<CompilationDatabasePlugin> Plugin(It->instantiate()); if (CompilationDatabase *DB = Plugin->loadFromDirectory(BuildDirectory, DatabaseErrorMessage)) return DB; @@ -52,7 +52,7 @@ CompilationDatabase::loadFromDirectory(StringRef BuildDirectory, ErrorStream << It->getName() << ": " << DatabaseErrorMessage << "\n"; } ErrorMessage = ErrorStream.str(); - return NULL; + return nullptr; } static CompilationDatabase * @@ -76,7 +76,7 @@ findCompilationDatabaseFromDirectory(StringRef Directory, Directory = llvm::sys::path::parent_path(Directory); } ErrorMessage = ErrorStream.str(); - return NULL; + return nullptr; } CompilationDatabase * @@ -151,14 +151,14 @@ private: // options. class UnusedInputDiagConsumer : public DiagnosticConsumer { public: - UnusedInputDiagConsumer() : Other(0) {} + UnusedInputDiagConsumer() : Other(nullptr) {} // Useful for debugging, chain diagnostics to another consumer after // recording for our own purposes. UnusedInputDiagConsumer(DiagnosticConsumer *Other) : Other(Other) {} virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, - const Diagnostic &Info) LLVM_OVERRIDE { + const Diagnostic &Info) override { if (Info.getID() == clang::diag::warn_drv_input_file_unused) { // Arg 1 for this diagnostic is the option that didn't get used. UnusedInputs.push_back(Info.getArgStdStr(0)); @@ -204,19 +204,19 @@ private: /// \li true if successful. /// \li false if \c Args cannot be used for compilation jobs (e.g. /// contains an option like -E or -version). -bool stripPositionalArgs(std::vector<const char *> Args, - std::vector<std::string> &Result) { +static bool stripPositionalArgs(std::vector<const char *> Args, + std::vector<std::string> &Result) { IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); UnusedInputDiagConsumer DiagClient; DiagnosticsEngine Diagnostics( IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts, &DiagClient, false); - // Neither clang executable nor default image name are required since the - // jobs the driver builds will not be executed. - OwningPtr<driver::Driver> NewDriver(new driver::Driver( + // The clang executable path isn't required since the jobs the driver builds + // will not be executed. + std::unique_ptr<driver::Driver> NewDriver(new driver::Driver( /* ClangExecutable= */ "", llvm::sys::getDefaultTargetTriple(), - /* DefaultImageName= */ "", Diagnostics)); + Diagnostics)); NewDriver->setCheckInputsExist(false); // This becomes the new argv[0]. The value is actually not important as it @@ -237,7 +237,13 @@ bool stripPositionalArgs(std::vector<const char *> Args, // up with no jobs but then this is the user's fault. Args.push_back("placeholder.cpp"); - const OwningPtr<driver::Compilation> Compilation( + // Remove -no-integrated-as; it's not used for syntax checking, + // and it confuses targets which don't support this option. + Args.erase(std::remove_if(Args.begin(), Args.end(), + MatchesAny(std::string("-no-integrated-as"))), + Args.end()); + + const std::unique_ptr<driver::Compilation> Compilation( NewDriver->BuildCompilation(Args)); const driver::JobList &Jobs = Compilation->getJobs(); @@ -271,6 +277,7 @@ bool stripPositionalArgs(std::vector<const char *> Args, End = std::remove_if(Args.begin(), End, MatchesAny(DiagClient.UnusedInputs)); // Remove the -c add above as well. It will be at the end right now. + assert(strcmp(*(End - 1), "-c") == 0); --End; Result = std::vector<std::string>(Args.begin() + 1, End); @@ -283,13 +290,13 @@ FixedCompilationDatabase::loadFromCommandLine(int &Argc, Twine Directory) { const char **DoubleDash = std::find(Argv, Argv + Argc, StringRef("--")); if (DoubleDash == Argv + Argc) - return NULL; + return nullptr; std::vector<const char *> CommandLine(DoubleDash + 1, Argv + Argc); Argc = DoubleDash - Argv; std::vector<std::string> StrippedArgs; if (!stripPositionalArgs(CommandLine, StrippedArgs)) - return 0; + return nullptr; return new FixedCompilationDatabase(Directory, StrippedArgs); } @@ -298,7 +305,8 @@ FixedCompilationDatabase(Twine Directory, ArrayRef<std::string> CommandLine) { std::vector<std::string> ToolCommandLine(1, "clang-tool"); ToolCommandLine.insert(ToolCommandLine.end(), CommandLine.begin(), CommandLine.end()); - CompileCommands.push_back(CompileCommand(Directory, ToolCommandLine)); + CompileCommands.push_back( + CompileCommand(Directory, std::move(ToolCommandLine))); } std::vector<CompileCommand> diff --git a/contrib/llvm/tools/clang/lib/Tooling/FileMatchTrie.cpp b/contrib/llvm/tools/clang/lib/Tooling/FileMatchTrie.cpp index 89979a8..dc9999e 100644 --- a/contrib/llvm/tools/clang/lib/Tooling/FileMatchTrie.cpp +++ b/contrib/llvm/tools/clang/lib/Tooling/FileMatchTrie.cpp @@ -24,7 +24,7 @@ namespace tooling { /// \brief Default \c PathComparator using \c llvm::sys::fs::equivalent(). struct DefaultPathComparator : public PathComparator { virtual ~DefaultPathComparator() {} - virtual bool equivalent(StringRef FileA, StringRef FileB) const { + bool equivalent(StringRef FileA, StringRef FileB) const override { return FileA == FileB || llvm::sys::fs::equivalent(FileA, FileB); } }; diff --git a/contrib/llvm/tools/clang/lib/Tooling/JSONCompilationDatabase.cpp b/contrib/llvm/tools/clang/lib/Tooling/JSONCompilationDatabase.cpp index 1e33b41..8b8bd29 100644 --- a/contrib/llvm/tools/clang/lib/Tooling/JSONCompilationDatabase.cpp +++ b/contrib/llvm/tools/clang/lib/Tooling/JSONCompilationDatabase.cpp @@ -17,7 +17,7 @@ #include "clang/Tooling/Tooling.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/Path.h" -#include "llvm/Support/system_error.h" +#include <system_error> namespace clang { namespace tooling { @@ -118,15 +118,15 @@ std::vector<std::string> unescapeCommandLine( } class JSONCompilationDatabasePlugin : public CompilationDatabasePlugin { - virtual CompilationDatabase *loadFromDirectory( - StringRef Directory, std::string &ErrorMessage) { + CompilationDatabase *loadFromDirectory(StringRef Directory, + std::string &ErrorMessage) override { SmallString<1024> JSONDatabasePath(Directory); llvm::sys::path::append(JSONDatabasePath, "compile_commands.json"); - OwningPtr<CompilationDatabase> Database( + std::unique_ptr<CompilationDatabase> Database( JSONCompilationDatabase::loadFromFile(JSONDatabasePath, ErrorMessage)); if (!Database) - return NULL; - return Database.take(); + return nullptr; + return Database.release(); } }; @@ -144,37 +144,36 @@ volatile int JSONAnchorSource = 0; JSONCompilationDatabase * JSONCompilationDatabase::loadFromFile(StringRef FilePath, std::string &ErrorMessage) { - OwningPtr<llvm::MemoryBuffer> DatabaseBuffer; - llvm::error_code Result = - llvm::MemoryBuffer::getFile(FilePath, DatabaseBuffer); - if (Result != 0) { + llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> DatabaseBuffer = + llvm::MemoryBuffer::getFile(FilePath); + if (std::error_code Result = DatabaseBuffer.getError()) { ErrorMessage = "Error while opening JSON database: " + Result.message(); - return NULL; + return nullptr; } - OwningPtr<JSONCompilationDatabase> Database( - new JSONCompilationDatabase(DatabaseBuffer.take())); + std::unique_ptr<JSONCompilationDatabase> Database( + new JSONCompilationDatabase(DatabaseBuffer->release())); if (!Database->parse(ErrorMessage)) - return NULL; - return Database.take(); + return nullptr; + return Database.release(); } JSONCompilationDatabase * JSONCompilationDatabase::loadFromBuffer(StringRef DatabaseString, std::string &ErrorMessage) { - OwningPtr<llvm::MemoryBuffer> DatabaseBuffer( + std::unique_ptr<llvm::MemoryBuffer> DatabaseBuffer( llvm::MemoryBuffer::getMemBuffer(DatabaseString)); - OwningPtr<JSONCompilationDatabase> Database( - new JSONCompilationDatabase(DatabaseBuffer.take())); + std::unique_ptr<JSONCompilationDatabase> Database( + new JSONCompilationDatabase(DatabaseBuffer.release())); if (!Database->parse(ErrorMessage)) - return NULL; - return Database.take(); + return nullptr; + return Database.release(); } std::vector<CompileCommand> JSONCompilationDatabase::getCompileCommands(StringRef FilePath) const { SmallString<128> NativeFilePath; llvm::sys::path::native(FilePath, NativeFilePath); - std::vector<StringRef> PossibleMatches; + std::string Error; llvm::raw_string_ostream ES(Error); StringRef Match = MatchTrie.findEquivalent(NativeFilePath.str(), ES); @@ -235,12 +234,12 @@ bool JSONCompilationDatabase::parse(std::string &ErrorMessage) { return false; } llvm::yaml::Node *Root = I->getRoot(); - if (Root == NULL) { + if (!Root) { ErrorMessage = "Error while parsing YAML."; return false; } llvm::yaml::SequenceNode *Array = dyn_cast<llvm::yaml::SequenceNode>(Root); - if (Array == NULL) { + if (!Array) { ErrorMessage = "Expected array."; return false; } @@ -248,30 +247,30 @@ bool JSONCompilationDatabase::parse(std::string &ErrorMessage) { AE = Array->end(); AI != AE; ++AI) { llvm::yaml::MappingNode *Object = dyn_cast<llvm::yaml::MappingNode>(&*AI); - if (Object == NULL) { + if (!Object) { ErrorMessage = "Expected object."; return false; } - llvm::yaml::ScalarNode *Directory = NULL; - llvm::yaml::ScalarNode *Command = NULL; - llvm::yaml::ScalarNode *File = NULL; + llvm::yaml::ScalarNode *Directory = nullptr; + llvm::yaml::ScalarNode *Command = nullptr; + llvm::yaml::ScalarNode *File = nullptr; for (llvm::yaml::MappingNode::iterator KVI = Object->begin(), KVE = Object->end(); KVI != KVE; ++KVI) { llvm::yaml::Node *Value = (*KVI).getValue(); - if (Value == NULL) { + if (!Value) { ErrorMessage = "Expected value."; return false; } llvm::yaml::ScalarNode *ValueString = dyn_cast<llvm::yaml::ScalarNode>(Value); - if (ValueString == NULL) { + if (!ValueString) { ErrorMessage = "Expected string as value."; return false; } llvm::yaml::ScalarNode *KeyString = dyn_cast<llvm::yaml::ScalarNode>((*KVI).getKey()); - if (KeyString == NULL) { + if (!KeyString) { ErrorMessage = "Expected strings as key."; return false; } diff --git a/contrib/llvm/tools/clang/lib/Tooling/Refactoring.cpp b/contrib/llvm/tools/clang/lib/Tooling/Refactoring.cpp index e165c12..c96b8c9 100644 --- a/contrib/llvm/tools/clang/lib/Tooling/Refactoring.cpp +++ b/contrib/llvm/tools/clang/lib/Tooling/Refactoring.cpp @@ -18,9 +18,9 @@ #include "clang/Lex/Lexer.h" #include "clang/Rewrite/Core/Rewriter.h" #include "clang/Tooling/Refactoring.h" -#include "llvm/Support/raw_os_ostream.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" +#include "llvm/Support/raw_os_ostream.h" namespace clang { namespace tooling { @@ -35,12 +35,13 @@ Replacement::Replacement(StringRef FilePath, unsigned Offset, unsigned Length, : FilePath(FilePath), ReplacementRange(Offset, Length), ReplacementText(ReplacementText) {} -Replacement::Replacement(SourceManager &Sources, SourceLocation Start, +Replacement::Replacement(const SourceManager &Sources, SourceLocation Start, unsigned Length, StringRef ReplacementText) { setFromSourceLocation(Sources, Start, Length, ReplacementText); } -Replacement::Replacement(SourceManager &Sources, const CharSourceRange &Range, +Replacement::Replacement(const SourceManager &Sources, + const CharSourceRange &Range, StringRef ReplacementText) { setFromSourceRange(Sources, Range, ReplacementText); } @@ -52,7 +53,7 @@ bool Replacement::isApplicable() const { bool Replacement::apply(Rewriter &Rewrite) const { SourceManager &SM = Rewrite.getSourceMgr(); const FileEntry *Entry = SM.getFileManager().getFile(FilePath); - if (Entry == NULL) + if (!Entry) return false; FileID ID; // FIXME: Use SM.translateFile directly. @@ -99,17 +100,17 @@ bool operator==(const Replacement &LHS, const Replacement &RHS) { LHS.getReplacementText() == RHS.getReplacementText(); } -void Replacement::setFromSourceLocation(SourceManager &Sources, +void Replacement::setFromSourceLocation(const SourceManager &Sources, SourceLocation Start, unsigned Length, StringRef ReplacementText) { const std::pair<FileID, unsigned> DecomposedLocation = Sources.getDecomposedLoc(Start); const FileEntry *Entry = Sources.getFileEntryForID(DecomposedLocation.first); - if (Entry != NULL) { + if (Entry) { // Make FilePath absolute so replacements can be applied correctly when // relative paths for files are used. llvm::SmallString<256> FilePath(Entry->getName()); - llvm::error_code EC = llvm::sys::fs::make_absolute(FilePath); + std::error_code EC = llvm::sys::fs::make_absolute(FilePath); this->FilePath = EC ? FilePath.c_str() : Entry->getName(); } else { this->FilePath = InvalidLocation; @@ -121,7 +122,8 @@ void Replacement::setFromSourceLocation(SourceManager &Sources, // FIXME: This should go into the Lexer, but we need to figure out how // to handle ranges for refactoring in general first - there is no obvious // good way how to integrate this into the Lexer yet. -static int getRangeSize(SourceManager &Sources, const CharSourceRange &Range) { +static int getRangeSize(const SourceManager &Sources, + const CharSourceRange &Range) { SourceLocation SpellingBegin = Sources.getSpellingLoc(Range.getBegin()); SourceLocation SpellingEnd = Sources.getSpellingLoc(Range.getEnd()); std::pair<FileID, unsigned> Start = Sources.getDecomposedLoc(SpellingBegin); @@ -133,7 +135,7 @@ static int getRangeSize(SourceManager &Sources, const CharSourceRange &Range) { return End.second - Start.second; } -void Replacement::setFromSourceRange(SourceManager &Sources, +void Replacement::setFromSourceRange(const SourceManager &Sources, const CharSourceRange &Range, StringRef ReplacementText) { setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()), diff --git a/contrib/llvm/tools/clang/lib/Tooling/Tooling.cpp b/contrib/llvm/tools/clang/lib/Tooling/Tooling.cpp index a58854d..0db38db 100644 --- a/contrib/llvm/tools/clang/lib/Tooling/Tooling.cpp +++ b/contrib/llvm/tools/clang/lib/Tooling/Tooling.cpp @@ -24,6 +24,7 @@ #include "clang/Tooling/ArgumentsAdjusters.h" #include "clang/Tooling/CompilationDatabase.h" #include "llvm/ADT/STLExtras.h" +#include "llvm/Config/llvm-config.h" #include "llvm/Option/Option.h" #include "llvm/Support/Debug.h" #include "llvm/Support/FileSystem.h" @@ -31,12 +32,14 @@ #include "llvm/Support/raw_ostream.h" // For chdir, see the comment in ClangTool::run for more information. -#ifdef _WIN32 +#ifdef LLVM_ON_WIN32 # include <direct.h> #else # include <unistd.h> #endif +#define DEBUG_TYPE "clang-tooling" + namespace clang { namespace tooling { @@ -51,10 +54,8 @@ FrontendActionFactory::~FrontendActionFactory() {} /// \brief Builds a clang driver initialized for running clang tools. static clang::driver::Driver *newDriver(clang::DiagnosticsEngine *Diagnostics, const char *BinaryName) { - const std::string DefaultOutputName = "a.out"; clang::driver::Driver *CompilerDriver = new clang::driver::Driver( - BinaryName, llvm::sys::getDefaultTargetTriple(), - DefaultOutputName, *Diagnostics); + BinaryName, llvm::sys::getDefaultTargetTriple(), *Diagnostics); CompilerDriver->setTitle("clang_based_tool"); return CompilerDriver; } @@ -74,7 +75,7 @@ static const llvm::opt::ArgStringList *getCC1Arguments( Jobs.Print(error_stream, "; ", true); Diagnostics->Report(clang::diag::err_fe_expected_compiler_job) << error_stream.str(); - return NULL; + return nullptr; } // The one job we find should be to invoke clang again. @@ -82,7 +83,7 @@ static const llvm::opt::ArgStringList *getCC1Arguments( cast<clang::driver::Command>(*Jobs.begin()); if (StringRef(Cmd->getCreator().getName()) != "clang") { Diagnostics->Report(clang::diag::err_fe_expected_clang_command); - return NULL; + return nullptr; } return &Cmd->getArguments(); @@ -99,6 +100,7 @@ static clang::CompilerInvocation *newInvocation( *Diagnostics); Invocation->getFrontendOpts().DisableFree = false; Invocation->getCodeGenOpts().DisableFree = false; + Invocation->getDependencyOutputOpts() = DependencyOutputOptions(); return Invocation; } @@ -127,7 +129,7 @@ bool runToolOnCodeWithArgs(clang::FrontendAction *ToolAction, const Twine &Code, llvm::IntrusiveRefCntPtr<FileManager> Files( new FileManager(FileSystemOptions())); ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef), ToolAction, - Files.getPtr()); + Files.get()); SmallString<1024> CodeStorage; Invocation.mapVirtualFile(FileNameRef, @@ -143,7 +145,7 @@ std::string getAbsolutePath(StringRef File) { } SmallString<1024> AbsolutePath = RelativePath; - llvm::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath); + std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath); assert(!EC); (void)EC; llvm::sys::path::native(AbsolutePath); @@ -158,26 +160,26 @@ class SingleFrontendActionFactory : public FrontendActionFactory { public: SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {} - FrontendAction *create() { return Action; } + FrontendAction *create() override { return Action; } }; } -ToolInvocation::ToolInvocation(ArrayRef<std::string> CommandLine, +ToolInvocation::ToolInvocation(std::vector<std::string> CommandLine, ToolAction *Action, FileManager *Files) - : CommandLine(CommandLine.vec()), + : CommandLine(std::move(CommandLine)), Action(Action), OwnsAction(false), Files(Files), - DiagConsumer(NULL) {} + DiagConsumer(nullptr) {} -ToolInvocation::ToolInvocation(ArrayRef<std::string> CommandLine, +ToolInvocation::ToolInvocation(std::vector<std::string> CommandLine, FrontendAction *FAction, FileManager *Files) - : CommandLine(CommandLine.vec()), + : CommandLine(std::move(CommandLine)), Action(new SingleFrontendActionFactory(FAction)), OwnsAction(true), Files(Files), - DiagConsumer(NULL) {} + DiagConsumer(nullptr) {} ToolInvocation::~ToolInvocation() { if (OwnsAction) @@ -196,8 +198,8 @@ void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) { bool ToolInvocation::run() { std::vector<const char*> Argv; - for (int I = 0, E = CommandLine.size(); I != E; ++I) - Argv.push_back(CommandLine[I].c_str()); + for (const std::string &Str : CommandLine) + Argv.push_back(Str.c_str()); const char *const BinaryName = Argv[0]; IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); TextDiagnosticPrinter DiagnosticPrinter( @@ -206,28 +208,25 @@ bool ToolInvocation::run() { IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts, DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false); - const OwningPtr<clang::driver::Driver> Driver( + const std::unique_ptr<clang::driver::Driver> Driver( newDriver(&Diagnostics, BinaryName)); // Since the input might only be virtual, don't check whether it exists. Driver->setCheckInputsExist(false); - const OwningPtr<clang::driver::Compilation> Compilation( + const std::unique_ptr<clang::driver::Compilation> Compilation( Driver->BuildCompilation(llvm::makeArrayRef(Argv))); const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments( &Diagnostics, Compilation.get()); - if (CC1Args == NULL) { + if (!CC1Args) { return false; } - OwningPtr<clang::CompilerInvocation> Invocation( + std::unique_ptr<clang::CompilerInvocation> Invocation( newInvocation(&Diagnostics, *CC1Args)); - for (llvm::StringMap<StringRef>::const_iterator - It = MappedFileContents.begin(), End = MappedFileContents.end(); - It != End; ++It) { + for (const auto &It : MappedFileContents) { // Inject the code as the given file name into the preprocessor options. - const llvm::MemoryBuffer *Input = - llvm::MemoryBuffer::getMemBuffer(It->getValue()); - Invocation->getPreprocessorOpts().addRemappedFile(It->getKey(), Input); + auto *Input = llvm::MemoryBuffer::getMemBuffer(It.getValue()); + Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(), Input); } - return runInvocation(BinaryName, Compilation.get(), Invocation.take()); + return runInvocation(BinaryName, Compilation.get(), Invocation.release()); } bool ToolInvocation::runInvocation( @@ -254,10 +253,10 @@ bool FrontendActionFactory::runInvocation(CompilerInvocation *Invocation, // The FrontendAction can have lifetime requirements for Compiler or its // members, and we need to ensure it's deleted earlier than Compiler. So we - // pass it to an OwningPtr declared after the Compiler variable. - OwningPtr<FrontendAction> ScopedToolAction(create()); + // pass it to an std::unique_ptr declared after the Compiler variable. + std::unique_ptr<FrontendAction> ScopedToolAction(create()); - // Create the compilers actual diagnostics engine. + // Create the compiler's actual diagnostics engine. Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false); if (!Compiler.hasDiagnostics()) return false; @@ -272,18 +271,18 @@ bool FrontendActionFactory::runInvocation(CompilerInvocation *Invocation, ClangTool::ClangTool(const CompilationDatabase &Compilations, ArrayRef<std::string> SourcePaths) - : Files(new FileManager(FileSystemOptions())), DiagConsumer(NULL) { + : Files(new FileManager(FileSystemOptions())), DiagConsumer(nullptr) { ArgsAdjusters.push_back(new ClangStripOutputAdjuster()); ArgsAdjusters.push_back(new ClangSyntaxOnlyAdjuster()); - for (unsigned I = 0, E = SourcePaths.size(); I != E; ++I) { - SmallString<1024> File(getAbsolutePath(SourcePaths[I])); + for (const auto &SourcePath : SourcePaths) { + std::string File(getAbsolutePath(SourcePath)); std::vector<CompileCommand> CompileCommandsForFile = - Compilations.getCompileCommands(File.str()); + Compilations.getCompileCommands(File); if (!CompileCommandsForFile.empty()) { - for (int I = 0, E = CompileCommandsForFile.size(); I != E; ++I) { - CompileCommands.push_back(std::make_pair(File.str(), - CompileCommandsForFile[I])); + for (CompileCommand &CompileCommand : CompileCommandsForFile) { + CompileCommands.push_back( + std::make_pair(File, std::move(CompileCommand))); } } else { // FIXME: There are two use cases here: doing a fuzzy @@ -291,7 +290,7 @@ ClangTool::ClangTool(const CompilationDatabase &Compilations, // about the .cc files that were not found, and the use case where I // specify all files I want to run over explicitly, where this should // be an error. We'll want to add an option for this. - llvm::outs() << "Skipping " << File << ". Command line not found.\n"; + llvm::errs() << "Skipping " << File << ". Compile command not found.\n"; } } } @@ -332,8 +331,7 @@ int ClangTool::run(ToolAction *Action) { llvm::sys::fs::getMainExecutable("clang_tool", &StaticSymbol); bool ProcessingFailed = false; - for (unsigned I = 0; I < CompileCommands.size(); ++I) { - std::string File = CompileCommands[I].first; + for (const auto &Command : CompileCommands) { // FIXME: chdir is thread hostile; on the other hand, creating the same // behavior as chdir is complex: chdir resolves the path once, thus // guaranteeing that all subsequent relative path operations work @@ -341,28 +339,27 @@ int ClangTool::run(ToolAction *Action) { // for example on network filesystems, where symlinks might be switched // during runtime of the tool. Fixing this depends on having a file system // abstraction that allows openat() style interactions. - if (chdir(CompileCommands[I].second.Directory.c_str())) + if (chdir(Command.second.Directory.c_str())) llvm::report_fatal_error("Cannot chdir into \"" + - CompileCommands[I].second.Directory + "\n!"); - std::vector<std::string> CommandLine = CompileCommands[I].second.CommandLine; - for (unsigned I = 0, E = ArgsAdjusters.size(); I != E; ++I) - CommandLine = ArgsAdjusters[I]->Adjust(CommandLine); + Twine(Command.second.Directory) + "\n!"); + std::vector<std::string> CommandLine = Command.second.CommandLine; + for (ArgumentsAdjuster *Adjuster : ArgsAdjusters) + CommandLine = Adjuster->Adjust(CommandLine); assert(!CommandLine.empty()); CommandLine[0] = MainExecutable; // FIXME: We need a callback mechanism for the tool writer to output a // customized message for each file. DEBUG({ - llvm::dbgs() << "Processing: " << File << ".\n"; + llvm::dbgs() << "Processing: " << Command.first << ".\n"; }); - ToolInvocation Invocation(CommandLine, Action, Files.getPtr()); + ToolInvocation Invocation(std::move(CommandLine), Action, Files.get()); Invocation.setDiagnosticConsumer(DiagConsumer); - for (int I = 0, E = MappedFileContents.size(); I != E; ++I) { - Invocation.mapVirtualFile(MappedFileContents[I].first, - MappedFileContents[I].second); + for (const auto &MappedFile : MappedFileContents) { + Invocation.mapVirtualFile(MappedFile.first, MappedFile.second); } if (!Invocation.run()) { // FIXME: Diagnostics should be used instead. - llvm::errs() << "Error while processing " << File << ".\n"; + llvm::errs() << "Error while processing " << Command.first << ".\n"; ProcessingFailed = true; } } @@ -372,55 +369,58 @@ int ClangTool::run(ToolAction *Action) { namespace { class ASTBuilderAction : public ToolAction { - std::vector<ASTUnit *> &ASTs; + std::vector<std::unique_ptr<ASTUnit>> &ASTs; public: - ASTBuilderAction(std::vector<ASTUnit *> &ASTs) : ASTs(ASTs) {} + ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {} bool runInvocation(CompilerInvocation *Invocation, FileManager *Files, - DiagnosticConsumer *DiagConsumer) { + DiagnosticConsumer *DiagConsumer) override { // FIXME: This should use the provided FileManager. - ASTUnit *AST = ASTUnit::LoadFromCompilerInvocation( + std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation( Invocation, CompilerInstance::createDiagnostics( &Invocation->getDiagnosticOpts(), DiagConsumer, /*ShouldOwnClient=*/false)); if (!AST) return false; - ASTs.push_back(AST); + ASTs.push_back(std::move(AST)); return true; } }; } -int ClangTool::buildASTs(std::vector<ASTUnit *> &ASTs) { +int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) { ASTBuilderAction Action(ASTs); return run(&Action); } -ASTUnit *buildASTFromCode(const Twine &Code, const Twine &FileName) { +std::unique_ptr<ASTUnit> buildASTFromCode(const Twine &Code, + const Twine &FileName) { return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName); } -ASTUnit *buildASTFromCodeWithArgs(const Twine &Code, - const std::vector<std::string> &Args, - const Twine &FileName) { +std::unique_ptr<ASTUnit> +buildASTFromCodeWithArgs(const Twine &Code, + const std::vector<std::string> &Args, + const Twine &FileName) { SmallString<16> FileNameStorage; StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage); - std::vector<ASTUnit *> ASTs; + std::vector<std::unique_ptr<ASTUnit>> ASTs; ASTBuilderAction Action(ASTs); - ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef), &Action, 0); + ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef), &Action, + nullptr); SmallString<1024> CodeStorage; Invocation.mapVirtualFile(FileNameRef, Code.toNullTerminatedStringRef(CodeStorage)); if (!Invocation.run()) - return 0; + return nullptr; assert(ASTs.size() == 1); - return ASTs[0]; + return std::move(ASTs[0]); } } // end namespace tooling |