diff options
Diffstat (limited to 'include/clang/Tooling')
-rw-r--r-- | include/clang/Tooling/ArgumentsAdjusters.h | 69 | ||||
-rw-r--r-- | include/clang/Tooling/CommonOptionsParser.h | 117 | ||||
-rw-r--r-- | include/clang/Tooling/CompilationDatabase.h | 222 | ||||
-rw-r--r-- | include/clang/Tooling/CompilationDatabasePluginRegistry.h | 27 | ||||
-rw-r--r-- | include/clang/Tooling/Core/Lookup.h | 48 | ||||
-rw-r--r-- | include/clang/Tooling/Core/Replacement.h | 241 | ||||
-rw-r--r-- | include/clang/Tooling/FileMatchTrie.h | 89 | ||||
-rw-r--r-- | include/clang/Tooling/JSONCompilationDatabase.h | 133 | ||||
-rw-r--r-- | include/clang/Tooling/Refactoring.h | 74 | ||||
-rw-r--r-- | include/clang/Tooling/RefactoringCallbacks.h | 90 | ||||
-rw-r--r-- | include/clang/Tooling/ReplacementsYaml.h | 76 | ||||
-rw-r--r-- | include/clang/Tooling/Tooling.h | 455 |
12 files changed, 0 insertions, 1641 deletions
diff --git a/include/clang/Tooling/ArgumentsAdjusters.h b/include/clang/Tooling/ArgumentsAdjusters.h deleted file mode 100644 index 1fd7be6..0000000 --- a/include/clang/Tooling/ArgumentsAdjusters.h +++ /dev/null @@ -1,69 +0,0 @@ -//===--- ArgumentsAdjusters.h - Command line arguments adjuster -*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file declares typedef ArgumentsAdjuster and functions to create several -// useful argument adjusters. -// ArgumentsAdjusters modify command line arguments obtained from a compilation -// database before they are used to run a frontend action. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLING_ARGUMENTSADJUSTERS_H -#define LLVM_CLANG_TOOLING_ARGUMENTSADJUSTERS_H - -#include "clang/Basic/LLVM.h" -#include "llvm/ADT/StringRef.h" -#include <functional> -#include <string> -#include <vector> - -namespace clang { -namespace tooling { - -/// \brief A sequence of command line arguments. -typedef std::vector<std::string> CommandLineArguments; - -/// \brief A prototype of a command line adjuster. -/// -/// Command line argument adjuster is responsible for command line arguments -/// modification before the arguments are used to run a frontend action. -typedef std::function<CommandLineArguments( - const CommandLineArguments &, StringRef Filename)> ArgumentsAdjuster; - -/// \brief Gets an argument adjuster that converts input command line arguments -/// to the "syntax check only" variant. -ArgumentsAdjuster getClangSyntaxOnlyAdjuster(); - -/// \brief Gets an argument adjuster which removes output-related command line -/// arguments. -ArgumentsAdjuster getClangStripOutputAdjuster(); - -enum class ArgumentInsertPosition { BEGIN, END }; - -/// \brief Gets an argument adjuster which inserts \p Extra arguments in the -/// specified position. -ArgumentsAdjuster getInsertArgumentAdjuster(const CommandLineArguments &Extra, - ArgumentInsertPosition Pos); - -/// \brief Gets an argument adjuster which inserts an \p Extra argument in the -/// specified position. -ArgumentsAdjuster getInsertArgumentAdjuster( - const char *Extra, - ArgumentInsertPosition Pos = ArgumentInsertPosition::END); - -/// \brief Gets an argument adjuster which adjusts the arguments in sequence -/// with the \p First adjuster and then with the \p Second one. -ArgumentsAdjuster combineAdjusters(ArgumentsAdjuster First, - ArgumentsAdjuster Second); - -} // namespace tooling -} // namespace clang - -#endif // LLVM_CLANG_TOOLING_ARGUMENTSADJUSTERS_H - diff --git a/include/clang/Tooling/CommonOptionsParser.h b/include/clang/Tooling/CommonOptionsParser.h deleted file mode 100644 index 1e8462c..0000000 --- a/include/clang/Tooling/CommonOptionsParser.h +++ /dev/null @@ -1,117 +0,0 @@ -//===- CommonOptionsParser.h - common options for clang tools -*- C++ -*-=====// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file implements the CommonOptionsParser class used to parse common -// command-line options for clang tools, so that they can be run as separate -// command-line applications with a consistent common interface for handling -// compilation database and input files. -// -// It provides a common subset of command-line options, common algorithm -// for locating a compilation database and source files, and help messages -// for the basic command-line interface. -// -// It creates a CompilationDatabase and reads common command-line options. -// -// This class uses the Clang Tooling infrastructure, see -// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html -// for details on setting it up with LLVM source tree. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLING_COMMONOPTIONSPARSER_H -#define LLVM_CLANG_TOOLING_COMMONOPTIONSPARSER_H - -#include "clang/Tooling/CompilationDatabase.h" -#include "llvm/Support/CommandLine.h" - -namespace clang { -namespace tooling { -/// \brief A parser for options common to all command-line Clang tools. -/// -/// Parses a common subset of command-line arguments, locates and loads a -/// compilation commands database and runs a tool with user-specified action. It -/// also contains a help message for the common command-line options. -/// -/// An example of usage: -/// \code -/// #include "clang/Frontend/FrontendActions.h" -/// #include "clang/Tooling/CommonOptionsParser.h" -/// #include "clang/Tooling/Tooling.h" -/// #include "llvm/Support/CommandLine.h" -/// -/// using namespace clang::tooling; -/// using namespace llvm; -/// -/// static cl::OptionCategory MyToolCategory("My tool options"); -/// static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); -/// static cl::extrahelp MoreHelp("\nMore help text..."); -/// static cl::opt<bool> YourOwnOption(...); -/// ... -/// -/// int main(int argc, const char **argv) { -/// CommonOptionsParser OptionsParser(argc, argv, MyToolCategory); -/// ClangTool Tool(OptionsParser.getCompilations(), -/// OptionsParser.getSourcePathList()); -/// return Tool.run(newFrontendActionFactory<SyntaxOnlyAction>().get()); -/// } -/// \endcode -class CommonOptionsParser { -public: - /// \brief Parses command-line, initializes a compilation database. - /// - /// This constructor can change argc and argv contents, e.g. consume - /// command-line options used for creating FixedCompilationDatabase. - /// - /// All options not belonging to \p Category become hidden. - /// - /// This constructor exits program in case of error. - CommonOptionsParser(int &argc, const char **argv, - llvm::cl::OptionCategory &Category, - const char *Overview = nullptr) - : CommonOptionsParser(argc, argv, Category, llvm::cl::OneOrMore, - Overview) {} - - /// \brief Parses command-line, initializes a compilation database. - /// - /// This constructor can change argc and argv contents, e.g. consume - /// command-line options used for creating FixedCompilationDatabase. - /// - /// All options not belonging to \p Category become hidden. - /// - /// I also allows calls to set the required number of positional parameters. - /// - /// This constructor exits program in case of error. - CommonOptionsParser(int &argc, const char **argv, - llvm::cl::OptionCategory &Category, - llvm::cl::NumOccurrencesFlag OccurrencesFlag, - const char *Overview = nullptr); - - /// Returns a reference to the loaded compilations database. - CompilationDatabase &getCompilations() { - return *Compilations; - } - - /// Returns a list of source file paths to process. - std::vector<std::string> getSourcePathList() { - return SourcePathList; - } - - static const char *const HelpMessage; - -private: - std::unique_ptr<CompilationDatabase> Compilations; - std::vector<std::string> SourcePathList; - std::vector<std::string> ExtraArgsBefore; - std::vector<std::string> ExtraArgsAfter; -}; - -} // namespace tooling -} // namespace clang - -#endif // LLVM_TOOLS_CLANG_INCLUDE_CLANG_TOOLING_COMMONOPTIONSPARSER_H diff --git a/include/clang/Tooling/CompilationDatabase.h b/include/clang/Tooling/CompilationDatabase.h deleted file mode 100644 index 08a0ffe..0000000 --- a/include/clang/Tooling/CompilationDatabase.h +++ /dev/null @@ -1,222 +0,0 @@ -//===--- CompilationDatabase.h - --------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file provides an interface and multiple implementations for -// CompilationDatabases. -// -// While C++ refactoring and analysis tools are not compilers, and thus -// don't run as part of the build system, they need the exact information -// of a build in order to be able to correctly understand the C++ code of -// the project. This information is provided via the CompilationDatabase -// interface. -// -// To create a CompilationDatabase from a build directory one can call -// CompilationDatabase::loadFromDirectory(), which deduces the correct -// compilation database from the root of the build tree. -// -// See the concrete subclasses of CompilationDatabase for currently supported -// formats. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLING_COMPILATIONDATABASE_H -#define LLVM_CLANG_TOOLING_COMPILATIONDATABASE_H - -#include "clang/Basic/LLVM.h" -#include "llvm/ADT/ArrayRef.h" -#include "llvm/ADT/StringRef.h" -#include "llvm/ADT/Twine.h" -#include <memory> -#include <string> -#include <vector> - -namespace clang { -namespace tooling { - -/// \brief Specifies the working directory and command of a compilation. -struct CompileCommand { - CompileCommand() {} - CompileCommand(Twine Directory, Twine Filename, - std::vector<std::string> CommandLine) - : Directory(Directory.str()), - Filename(Filename.str()), - CommandLine(std::move(CommandLine)) {} - - /// \brief The working directory the command was executed from. - std::string Directory; - - /// The source file associated with the command. - std::string Filename; - - /// \brief The command line that was executed. - std::vector<std::string> CommandLine; - - /// \brief An optional mapping from each file's path to its content for all - /// files needed for the compilation that are not available via the file - /// system. - /// - /// Note that a tool implementation is required to fall back to the file - /// system if a source file is not provided in the mapped sources, as - /// compilation databases will usually not provide all files in mapped sources - /// for performance reasons. - std::vector<std::pair<std::string, std::string> > MappedSources; -}; - -/// \brief Interface for compilation databases. -/// -/// A compilation database allows the user to retrieve all compile command lines -/// that a specified file is compiled with in a project. -/// The retrieved compile command lines can be used to run clang tools over -/// a subset of the files in a project. -class CompilationDatabase { -public: - virtual ~CompilationDatabase(); - - /// \brief Loads a compilation database from a build directory. - /// - /// Looks at the specified 'BuildDirectory' and creates a compilation database - /// that allows to query compile commands for source files in the - /// corresponding source tree. - /// - /// Returns NULL and sets ErrorMessage if we were not able to build up a - /// compilation database for the build directory. - /// - /// FIXME: Currently only supports JSON compilation databases, which - /// are named 'compile_commands.json' in the given directory. Extend this - /// for other build types (like ninja build files). - static std::unique_ptr<CompilationDatabase> - loadFromDirectory(StringRef BuildDirectory, std::string &ErrorMessage); - - /// \brief Tries to detect a compilation database location and load it. - /// - /// Looks for a compilation database in all parent paths of file 'SourceFile' - /// by calling loadFromDirectory. - static std::unique_ptr<CompilationDatabase> - autoDetectFromSource(StringRef SourceFile, std::string &ErrorMessage); - - /// \brief Tries to detect a compilation database location and load it. - /// - /// Looks for a compilation database in directory 'SourceDir' and all - /// its parent paths by calling loadFromDirectory. - static std::unique_ptr<CompilationDatabase> - autoDetectFromDirectory(StringRef SourceDir, std::string &ErrorMessage); - - /// \brief Returns all compile commands in which the specified file was - /// compiled. - /// - /// This includes compile comamnds that span multiple source files. - /// For example, consider a project with the following compilations: - /// $ clang++ -o test a.cc b.cc t.cc - /// $ clang++ -o production a.cc b.cc -DPRODUCTION - /// A compilation database representing the project would return both command - /// lines for a.cc and b.cc and only the first command line for t.cc. - virtual std::vector<CompileCommand> getCompileCommands( - StringRef FilePath) const = 0; - - /// \brief Returns the list of all files available in the compilation database. - virtual std::vector<std::string> getAllFiles() const = 0; - - /// \brief Returns all compile commands for all the files in the compilation - /// database. - /// - /// FIXME: Add a layer in Tooling that provides an interface to run a tool - /// over all files in a compilation database. Not all build systems have the - /// ability to provide a feasible implementation for \c getAllCompileCommands. - virtual std::vector<CompileCommand> getAllCompileCommands() const = 0; -}; - -/// \brief Interface for compilation database plugins. -/// -/// A compilation database plugin allows the user to register custom compilation -/// databases that are picked up as compilation database if the corresponding -/// library is linked in. To register a plugin, declare a static variable like: -/// -/// \code -/// static CompilationDatabasePluginRegistry::Add<MyDatabasePlugin> -/// X("my-compilation-database", "Reads my own compilation database"); -/// \endcode -class CompilationDatabasePlugin { -public: - virtual ~CompilationDatabasePlugin(); - - /// \brief Loads a compilation database from a build directory. - /// - /// \see CompilationDatabase::loadFromDirectory(). - virtual std::unique_ptr<CompilationDatabase> - loadFromDirectory(StringRef Directory, std::string &ErrorMessage) = 0; -}; - -/// \brief A compilation database that returns a single compile command line. -/// -/// Useful when we want a tool to behave more like a compiler invocation. -class FixedCompilationDatabase : public CompilationDatabase { -public: - /// \brief Creates a FixedCompilationDatabase from the arguments after "--". - /// - /// Parses the given command line for "--". If "--" is found, the rest of - /// the arguments will make up the command line in the returned - /// FixedCompilationDatabase. - /// The arguments after "--" must not include positional parameters or the - /// argv[0] of the tool. Those will be added by the FixedCompilationDatabase - /// when a CompileCommand is requested. The argv[0] of the returned command - /// line will be "clang-tool". - /// - /// Returns NULL in case "--" is not found. - /// - /// The argument list is meant to be compatible with normal llvm command line - /// parsing in main methods. - /// int main(int argc, char **argv) { - /// std::unique_ptr<FixedCompilationDatabase> Compilations( - /// FixedCompilationDatabase::loadFromCommandLine(argc, argv)); - /// cl::ParseCommandLineOptions(argc, argv); - /// ... - /// } - /// - /// \param Argc The number of command line arguments - will be changed to - /// the number of arguments before "--", if "--" was found in the argument - /// list. - /// \param Argv Points to the command line arguments. - /// \param Directory The base directory used in the FixedCompilationDatabase. - static FixedCompilationDatabase *loadFromCommandLine(int &Argc, - const char *const *Argv, - Twine Directory = "."); - - /// \brief Constructs a compilation data base from a specified directory - /// and command line. - FixedCompilationDatabase(Twine Directory, ArrayRef<std::string> CommandLine); - - /// \brief Returns the given compile command. - /// - /// Will always return a vector with one entry that contains the directory - /// and command line specified at construction with "clang-tool" as argv[0] - /// and 'FilePath' as positional argument. - std::vector<CompileCommand> - getCompileCommands(StringRef FilePath) const override; - - /// \brief Returns the list of all files available in the compilation database. - /// - /// Note: This is always an empty list for the fixed compilation database. - std::vector<std::string> getAllFiles() const override; - - /// \brief Returns all compile commands for all the files in the compilation - /// database. - /// - /// Note: This is always an empty list for the fixed compilation database. - std::vector<CompileCommand> getAllCompileCommands() const override; - -private: - /// This is built up to contain a single entry vector to be returned from - /// getCompileCommands after adding the positional argument. - std::vector<CompileCommand> CompileCommands; -}; - -} // end namespace tooling -} // end namespace clang - -#endif diff --git a/include/clang/Tooling/CompilationDatabasePluginRegistry.h b/include/clang/Tooling/CompilationDatabasePluginRegistry.h deleted file mode 100644 index 7323ec8..0000000 --- a/include/clang/Tooling/CompilationDatabasePluginRegistry.h +++ /dev/null @@ -1,27 +0,0 @@ -//===--- CompilationDatabasePluginRegistry.h - ------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLING_COMPILATIONDATABASEPLUGINREGISTRY_H -#define LLVM_CLANG_TOOLING_COMPILATIONDATABASEPLUGINREGISTRY_H - -#include "clang/Tooling/CompilationDatabase.h" -#include "llvm/Support/Registry.h" - -namespace clang { -namespace tooling { - -class CompilationDatabasePlugin; - -typedef llvm::Registry<CompilationDatabasePlugin> - CompilationDatabasePluginRegistry; - -} // end namespace tooling -} // end namespace clang - -#endif diff --git a/include/clang/Tooling/Core/Lookup.h b/include/clang/Tooling/Core/Lookup.h deleted file mode 100644 index bc2b4db..0000000 --- a/include/clang/Tooling/Core/Lookup.h +++ /dev/null @@ -1,48 +0,0 @@ -//===--- Lookup.h - Framework for clang refactoring tools --*- C++ -*------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines helper methods for clang tools performing name lookup. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLING_CORE_LOOKUP_H -#define LLVM_CLANG_TOOLING_CORE_LOOKUP_H - -#include "clang/Basic/LLVM.h" -#include <string> - -namespace clang { - -class DeclContext; -class NamedDecl; -class NestedNameSpecifier; - -namespace tooling { - -/// Emulate a lookup to replace one nested name specifier with another using as -/// few additional namespace qualifications as possible. -/// -/// This does not perform a full C++ lookup so ADL will not work. -/// -/// \param Use The nested name to be replaced. -/// \param UseContext The context in which the nested name is contained. This -/// will be used to minimize namespace qualifications. -/// \param FromDecl The declaration to which the nested name points. -/// \param ReplacementString The replacement nested name. Must be fully -/// qualified including a leading "::". -/// \returns The new name to be inserted in place of the current nested name. -std::string replaceNestedName(const NestedNameSpecifier *Use, - const DeclContext *UseContext, - const NamedDecl *FromDecl, - StringRef ReplacementString); - -} // end namespace tooling -} // end namespace clang - -#endif // LLVM_CLANG_TOOLING_CORE_LOOKUP_H diff --git a/include/clang/Tooling/Core/Replacement.h b/include/clang/Tooling/Core/Replacement.h deleted file mode 100644 index 37389ac..0000000 --- a/include/clang/Tooling/Core/Replacement.h +++ /dev/null @@ -1,241 +0,0 @@ -//===--- Replacement.h - Framework for clang refactoring tools --*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// Classes supporting refactorings that span multiple translation units. -// While single translation unit refactorings are supported via the Rewriter, -// when refactoring multiple translation units changes must be stored in a -// SourceManager independent form, duplicate changes need to be removed, and -// all changes must be applied at once at the end of the refactoring so that -// the code is always parseable. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLING_CORE_REPLACEMENT_H -#define LLVM_CLANG_TOOLING_CORE_REPLACEMENT_H - -#include "clang/Basic/LangOptions.h" -#include "clang/Basic/SourceLocation.h" -#include "llvm/ADT/StringRef.h" -#include <set> -#include <string> -#include <vector> - -namespace clang { - -class Rewriter; - -namespace tooling { - -/// \brief A source range independent of the \c SourceManager. -class Range { -public: - Range() : Offset(0), Length(0) {} - Range(unsigned Offset, unsigned Length) : Offset(Offset), Length(Length) {} - - /// \brief Accessors. - /// @{ - unsigned getOffset() const { return Offset; } - unsigned getLength() const { return Length; } - /// @} - - /// \name Range Predicates - /// @{ - /// \brief Whether this range overlaps with \p RHS or not. - bool overlapsWith(Range RHS) const { - return Offset + Length > RHS.Offset && Offset < RHS.Offset + RHS.Length; - } - - /// \brief Whether this range contains \p RHS or not. - bool contains(Range RHS) const { - return RHS.Offset >= Offset && - (RHS.Offset + RHS.Length) <= (Offset + Length); - } - /// @} - -private: - unsigned Offset; - unsigned Length; -}; - -/// \brief A text replacement. -/// -/// Represents a SourceManager independent replacement of a range of text in a -/// specific file. -class Replacement { -public: - /// \brief Creates an invalid (not applicable) replacement. - Replacement(); - - /// \brief Creates a replacement of the range [Offset, Offset+Length) in - /// FilePath with ReplacementText. - /// - /// \param FilePath A source file accessible via a SourceManager. - /// \param Offset The byte offset of the start of the range in the file. - /// \param Length The length of the range in bytes. - Replacement(StringRef FilePath, unsigned Offset, unsigned Length, - StringRef ReplacementText); - - /// \brief Creates a Replacement of the range [Start, Start+Length) with - /// ReplacementText. - Replacement(const SourceManager &Sources, SourceLocation Start, - unsigned Length, StringRef ReplacementText); - - /// \brief Creates a Replacement of the given range with ReplacementText. - Replacement(const SourceManager &Sources, const CharSourceRange &Range, - StringRef ReplacementText, - const LangOptions &LangOpts = LangOptions()); - - /// \brief Creates a Replacement of the node with ReplacementText. - template <typename Node> - Replacement(const SourceManager &Sources, const Node &NodeToReplace, - StringRef ReplacementText, - const LangOptions &LangOpts = LangOptions()); - - /// \brief Returns whether this replacement can be applied to a file. - /// - /// Only replacements that are in a valid file can be applied. - bool isApplicable() const; - - /// \brief Accessors. - /// @{ - StringRef getFilePath() const { return FilePath; } - unsigned getOffset() const { return ReplacementRange.getOffset(); } - unsigned getLength() const { return ReplacementRange.getLength(); } - StringRef getReplacementText() const { return ReplacementText; } - /// @} - - /// \brief Applies the replacement on the Rewriter. - bool apply(Rewriter &Rewrite) const; - - /// \brief Returns a human readable string representation. - std::string toString() const; - - private: - void setFromSourceLocation(const SourceManager &Sources, - SourceLocation Start, unsigned Length, - StringRef ReplacementText); - void setFromSourceRange(const SourceManager &Sources, - const CharSourceRange &Range, - StringRef ReplacementText, - const LangOptions &LangOpts); - - std::string FilePath; - Range ReplacementRange; - std::string ReplacementText; -}; - -/// \brief Less-than operator between two Replacements. -bool operator<(const Replacement &LHS, const Replacement &RHS); - -/// \brief Equal-to operator between two Replacements. -bool operator==(const Replacement &LHS, const Replacement &RHS); - -/// \brief A set of Replacements. -/// FIXME: Change to a vector and deduplicate in the RefactoringTool. -typedef std::set<Replacement> Replacements; - -/// \brief Apply all replacements in \p Replaces to the Rewriter \p Rewrite. -/// -/// Replacement applications happen independently of the success of -/// other applications. -/// -/// \returns true if all replacements apply. false otherwise. -bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite); - -/// \brief Apply all replacements in \p Replaces to the Rewriter \p Rewrite. -/// -/// Replacement applications happen independently of the success of -/// other applications. -/// -/// \returns true if all replacements apply. false otherwise. -bool applyAllReplacements(const std::vector<Replacement> &Replaces, - Rewriter &Rewrite); - -/// \brief Applies all replacements in \p Replaces to \p Code. -/// -/// This completely ignores the path stored in each replacement. If one or more -/// replacements cannot be applied, this returns an empty \c string. -std::string applyAllReplacements(StringRef Code, const Replacements &Replaces); - -/// \brief Calculates how a code \p Position is shifted when \p Replaces are -/// applied. -unsigned shiftedCodePosition(const Replacements& Replaces, unsigned Position); - -/// \brief Calculates how a code \p Position is shifted when \p Replaces are -/// applied. -/// -/// \pre Replaces[i].getOffset() <= Replaces[i+1].getOffset(). -unsigned shiftedCodePosition(const std::vector<Replacement> &Replaces, - unsigned Position); - -/// \brief Removes duplicate Replacements and reports if Replacements conflict -/// with one another. All Replacements are assumed to be in the same file. -/// -/// \post Replaces[i].getOffset() <= Replaces[i+1].getOffset(). -/// -/// This function sorts \p Replaces so that conflicts can be reported simply by -/// offset into \p Replaces and number of elements in the conflict. -void deduplicate(std::vector<Replacement> &Replaces, - std::vector<Range> &Conflicts); - -/// \brief Collection of Replacements generated from a single translation unit. -struct TranslationUnitReplacements { - /// Name of the main source for the translation unit. - std::string MainSourceFile; - - /// A freeform chunk of text to describe the context of the replacements. - /// Will be printed, for example, when detecting conflicts during replacement - /// deduplication. - std::string Context; - - std::vector<Replacement> Replacements; -}; - -/// \brief Apply all replacements in \p Replaces to the Rewriter \p Rewrite. -/// -/// Replacement applications happen independently of the success of -/// other applications. -/// -/// \returns true if all replacements apply. false otherwise. -bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite); - -/// \brief Apply all replacements in \p Replaces to the Rewriter \p Rewrite. -/// -/// Replacement applications happen independently of the success of -/// other applications. -/// -/// \returns true if all replacements apply. false otherwise. -bool applyAllReplacements(const std::vector<Replacement> &Replaces, - Rewriter &Rewrite); - -/// \brief Applies all replacements in \p Replaces to \p Code. -/// -/// This completely ignores the path stored in each replacement. If one or more -/// replacements cannot be applied, this returns an empty \c string. -std::string applyAllReplacements(StringRef Code, const Replacements &Replaces); - -/// \brief Merges two sets of replacements with the second set referring to the -/// code after applying the first set. Within both 'First' and 'Second', -/// replacements must not overlap. -Replacements mergeReplacements(const Replacements &First, - const Replacements &Second); - -template <typename Node> -Replacement::Replacement(const SourceManager &Sources, - const Node &NodeToReplace, StringRef ReplacementText, - const LangOptions &LangOpts) { - const CharSourceRange Range = - CharSourceRange::getTokenRange(NodeToReplace->getSourceRange()); - setFromSourceRange(Sources, Range, ReplacementText, LangOpts); -} - -} // end namespace tooling -} // end namespace clang - -#endif // LLVM_CLANG_TOOLING_CORE_REPLACEMENT_H diff --git a/include/clang/Tooling/FileMatchTrie.h b/include/clang/Tooling/FileMatchTrie.h deleted file mode 100644 index 745c164..0000000 --- a/include/clang/Tooling/FileMatchTrie.h +++ /dev/null @@ -1,89 +0,0 @@ -//===--- FileMatchTrie.h - --------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file implements a match trie to find the matching file in a compilation -// database based on a given path in the presence of symlinks. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLING_FILEMATCHTRIE_H -#define LLVM_CLANG_TOOLING_FILEMATCHTRIE_H - -#include "clang/Basic/LLVM.h" -#include "llvm/ADT/StringRef.h" -#include <memory> -#include <string> -#include <vector> - -namespace clang { -namespace tooling { - -struct PathComparator { - virtual ~PathComparator() {} - virtual bool equivalent(StringRef FileA, StringRef FileB) const = 0; -}; -class FileMatchTrieNode; - -/// \brief A trie to efficiently match against the entries of the compilation -/// database in order of matching suffix length. -/// -/// When a clang tool is supposed to operate on a specific file, we have to -/// find the corresponding file in the compilation database. Although entries -/// in the compilation database are keyed by filename, a simple string match -/// is insufficient because of symlinks. Commonly, a project hierarchy looks -/// like this: -/// /<project-root>/src/<path>/<somefile>.cc (used as input for the tool) -/// /<project-root>/build/<symlink-to-src>/<path>/<somefile>.cc (stored in DB) -/// -/// Furthermore, there might be symlinks inside the source folder or inside the -/// database, so that the same source file is translated with different build -/// options. -/// -/// For a given input file, the \c FileMatchTrie finds its entries in order -/// of matching suffix length. For each suffix length, there might be one or -/// more entries in the database. For each of those entries, it calls -/// \c llvm::sys::fs::equivalent() (injected as \c PathComparator). There might -/// be zero or more entries with the same matching suffix length that are -/// equivalent to the input file. Three cases are distinguished: -/// 0 equivalent files: Continue with the next suffix length. -/// 1 equivalent file: Best match found, return it. -/// >1 equivalent files: Match is ambiguous, return error. -class FileMatchTrie { -public: - FileMatchTrie(); - - /// \brief Construct a new \c FileMatchTrie with the given \c PathComparator. - /// - /// The \c FileMatchTrie takes ownership of 'Comparator'. Used for testing. - FileMatchTrie(PathComparator* Comparator); - - ~FileMatchTrie(); - - /// \brief Insert a new absolute path. Relative paths are ignored. - void insert(StringRef NewPath); - - /// \brief Finds the corresponding file in this trie. - /// - /// Returns file name stored in this trie that is equivalent to 'FileName' - /// according to 'Comparator', if it can be uniquely identified. If there - /// are no matches an empty \c StringRef is returned. If there are ambigious - /// matches, an empty \c StringRef is returned and a corresponding message - /// written to 'Error'. - StringRef findEquivalent(StringRef FileName, - raw_ostream &Error) const; -private: - FileMatchTrieNode *Root; - std::unique_ptr<PathComparator> Comparator; -}; - - -} // end namespace tooling -} // end namespace clang - -#endif diff --git a/include/clang/Tooling/JSONCompilationDatabase.h b/include/clang/Tooling/JSONCompilationDatabase.h deleted file mode 100644 index 2a13fc1..0000000 --- a/include/clang/Tooling/JSONCompilationDatabase.h +++ /dev/null @@ -1,133 +0,0 @@ -//===--- JSONCompilationDatabase.h - ----------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// The JSONCompilationDatabase finds compilation databases supplied as a file -// 'compile_commands.json'. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLING_JSONCOMPILATIONDATABASE_H -#define LLVM_CLANG_TOOLING_JSONCOMPILATIONDATABASE_H - -#include "clang/Basic/LLVM.h" -#include "clang/Tooling/CompilationDatabase.h" -#include "clang/Tooling/FileMatchTrie.h" -#include "llvm/ADT/StringMap.h" -#include "llvm/ADT/StringRef.h" -#include "llvm/Support/MemoryBuffer.h" -#include "llvm/Support/SourceMgr.h" -#include "llvm/Support/YAMLParser.h" -#include <memory> -#include <string> -#include <vector> - -namespace clang { -namespace tooling { - -/// \brief A JSON based compilation database. -/// -/// JSON compilation database files must contain a list of JSON objects which -/// provide the command lines in the attributes 'directory', 'command', -/// 'arguments' and 'file': -/// [ -/// { "directory": "<working directory of the compile>", -/// "command": "<compile command line>", -/// "file": "<path to source file>" -/// }, -/// { "directory": "<working directory of the compile>", -/// "arguments": ["<raw>", "<command>" "<line>" "<parameters>"], -/// "file": "<path to source file>" -/// }, -/// ... -/// ] -/// Each object entry defines one compile action. The specified file is -/// considered to be the main source file for the translation unit. -/// -/// 'command' is a full command line that will be unescaped. -/// -/// 'arguments' is a list of command line arguments that will not be unescaped. -/// -/// JSON compilation databases can for example be generated in CMake projects -/// by setting the flag -DCMAKE_EXPORT_COMPILE_COMMANDS. -class JSONCompilationDatabase : public CompilationDatabase { -public: - /// \brief Loads a JSON compilation database from the specified file. - /// - /// Returns NULL and sets ErrorMessage if the database could not be - /// loaded from the given file. - static std::unique_ptr<JSONCompilationDatabase> - loadFromFile(StringRef FilePath, std::string &ErrorMessage); - - /// \brief Loads a JSON compilation database from a data buffer. - /// - /// Returns NULL and sets ErrorMessage if the database could not be loaded. - static std::unique_ptr<JSONCompilationDatabase> - loadFromBuffer(StringRef DatabaseString, std::string &ErrorMessage); - - /// \brief Returns all compile comamnds in which the specified file was - /// compiled. - /// - /// FIXME: Currently FilePath must be an absolute path inside the - /// source directory which does not have symlinks resolved. - std::vector<CompileCommand> - getCompileCommands(StringRef FilePath) const override; - - /// \brief Returns the list of all files available in the compilation database. - /// - /// These are the 'file' entries of the JSON objects. - std::vector<std::string> getAllFiles() const override; - - /// \brief Returns all compile commands for all the files in the compilation - /// database. - std::vector<CompileCommand> getAllCompileCommands() const override; - -private: - /// \brief Constructs a JSON compilation database on a memory buffer. - JSONCompilationDatabase(std::unique_ptr<llvm::MemoryBuffer> Database) - : Database(std::move(Database)), - YAMLStream(this->Database->getBuffer(), SM) {} - - /// \brief Parses the database file and creates the index. - /// - /// Returns whether parsing succeeded. Sets ErrorMessage if parsing - /// failed. - bool parse(std::string &ErrorMessage); - - // Tuple (directory, filename, commandline) where 'commandline' points to the - // corresponding scalar nodes in the YAML stream. - // If the command line contains a single argument, it is a shell-escaped - // command line. - // Otherwise, each entry in the command line vector is a literal - // argument to the compiler. - typedef std::tuple<llvm::yaml::ScalarNode *, - llvm::yaml::ScalarNode *, - std::vector<llvm::yaml::ScalarNode *>> CompileCommandRef; - - /// \brief Converts the given array of CompileCommandRefs to CompileCommands. - void getCommands(ArrayRef<CompileCommandRef> CommandsRef, - std::vector<CompileCommand> &Commands) const; - - // Maps file paths to the compile command lines for that file. - llvm::StringMap<std::vector<CompileCommandRef>> IndexByFile; - - /// All the compile commands in the order that they were provided in the - /// JSON stream. - std::vector<CompileCommandRef> AllCommands; - - FileMatchTrie MatchTrie; - - std::unique_ptr<llvm::MemoryBuffer> Database; - llvm::SourceMgr SM; - llvm::yaml::Stream YAMLStream; -}; - -} // end namespace tooling -} // end namespace clang - -#endif diff --git a/include/clang/Tooling/Refactoring.h b/include/clang/Tooling/Refactoring.h deleted file mode 100644 index 54deff6..0000000 --- a/include/clang/Tooling/Refactoring.h +++ /dev/null @@ -1,74 +0,0 @@ -//===--- Refactoring.h - Framework for clang refactoring tools --*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// Interfaces supporting refactorings that span multiple translation units. -// While single translation unit refactorings are supported via the Rewriter, -// when refactoring multiple translation units changes must be stored in a -// SourceManager independent form, duplicate changes need to be removed, and -// all changes must be applied at once at the end of the refactoring so that -// the code is always parseable. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLING_REFACTORING_H -#define LLVM_CLANG_TOOLING_REFACTORING_H - -#include "clang/Tooling/Core/Replacement.h" -#include "clang/Tooling/Tooling.h" -#include <string> - -namespace clang { - -class Rewriter; - -namespace tooling { - -/// \brief A tool to run refactorings. -/// -/// This is a refactoring specific version of \see ClangTool. FrontendActions -/// passed to run() and runAndSave() should add replacements to -/// getReplacements(). -class RefactoringTool : public ClangTool { -public: - /// \see ClangTool::ClangTool. - RefactoringTool(const CompilationDatabase &Compilations, - ArrayRef<std::string> SourcePaths, - std::shared_ptr<PCHContainerOperations> PCHContainerOps = - std::make_shared<PCHContainerOperations>()); - - /// \brief Returns the set of replacements to which replacements should - /// be added during the run of the tool. - Replacements &getReplacements(); - - /// \brief Call run(), apply all generated replacements, and immediately save - /// the results to disk. - /// - /// \returns 0 upon success. Non-zero upon failure. - int runAndSave(FrontendActionFactory *ActionFactory); - - /// \brief Apply all stored replacements to the given Rewriter. - /// - /// Replacement applications happen independently of the success of other - /// applications. - /// - /// \returns true if all replacements apply. false otherwise. - bool applyAllReplacements(Rewriter &Rewrite); - -private: - /// \brief Write all refactored files to disk. - int saveRewrittenFiles(Rewriter &Rewrite); - -private: - Replacements Replace; -}; - -} // end namespace tooling -} // end namespace clang - -#endif // LLVM_CLANG_TOOLING_REFACTORING_H diff --git a/include/clang/Tooling/RefactoringCallbacks.h b/include/clang/Tooling/RefactoringCallbacks.h deleted file mode 100644 index 6ef9ea1..0000000 --- a/include/clang/Tooling/RefactoringCallbacks.h +++ /dev/null @@ -1,90 +0,0 @@ -//===--- RefactoringCallbacks.h - Structural query framework ----*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// Provides callbacks to make common kinds of refactorings easy. -// -// The general idea is to construct a matcher expression that describes a -// subtree match on the AST and then replace the corresponding source code -// either by some specific text or some other AST node. -// -// Example: -// int main(int argc, char **argv) { -// ClangTool Tool(argc, argv); -// MatchFinder Finder; -// ReplaceStmtWithText Callback("integer", "42"); -// Finder.AddMatcher(id("integer", expression(integerLiteral())), Callback); -// return Tool.run(newFrontendActionFactory(&Finder)); -// } -// -// This will replace all integer literals with "42". -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLING_REFACTORINGCALLBACKS_H -#define LLVM_CLANG_TOOLING_REFACTORINGCALLBACKS_H - -#include "clang/ASTMatchers/ASTMatchFinder.h" -#include "clang/Tooling/Refactoring.h" - -namespace clang { -namespace tooling { - -/// \brief Base class for RefactoringCallbacks. -/// -/// Collects \c tooling::Replacements while running. -class RefactoringCallback : public ast_matchers::MatchFinder::MatchCallback { -public: - RefactoringCallback(); - Replacements &getReplacements(); - -protected: - Replacements Replace; -}; - -/// \brief Replace the text of the statement bound to \c FromId with the text in -/// \c ToText. -class ReplaceStmtWithText : public RefactoringCallback { -public: - ReplaceStmtWithText(StringRef FromId, StringRef ToText); - void run(const ast_matchers::MatchFinder::MatchResult &Result) override; - -private: - std::string FromId; - std::string ToText; -}; - -/// \brief Replace the text of the statement bound to \c FromId with the text of -/// the statement bound to \c ToId. -class ReplaceStmtWithStmt : public RefactoringCallback { -public: - ReplaceStmtWithStmt(StringRef FromId, StringRef ToId); - void run(const ast_matchers::MatchFinder::MatchResult &Result) override; - -private: - std::string FromId; - std::string ToId; -}; - -/// \brief Replace an if-statement bound to \c Id with the outdented text of its -/// body, choosing the consequent or the alternative based on whether -/// \c PickTrueBranch is true. -class ReplaceIfStmtWithItsBody : public RefactoringCallback { -public: - ReplaceIfStmtWithItsBody(StringRef Id, bool PickTrueBranch); - void run(const ast_matchers::MatchFinder::MatchResult &Result) override; - -private: - std::string Id; - const bool PickTrueBranch; -}; - -} // end namespace tooling -} // end namespace clang - -#endif diff --git a/include/clang/Tooling/ReplacementsYaml.h b/include/clang/Tooling/ReplacementsYaml.h deleted file mode 100644 index 4a7666d..0000000 --- a/include/clang/Tooling/ReplacementsYaml.h +++ /dev/null @@ -1,76 +0,0 @@ -//===-- ReplacementsYaml.h -- Serialiazation for Replacements ---*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -/// -/// \file -/// \brief This file defines the structure of a YAML document for serializing -/// replacements. -/// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLING_REPLACEMENTSYAML_H -#define LLVM_CLANG_TOOLING_REPLACEMENTSYAML_H - -#include "clang/Tooling/Refactoring.h" -#include "llvm/Support/YAMLTraits.h" -#include <string> -#include <vector> - -LLVM_YAML_IS_SEQUENCE_VECTOR(clang::tooling::Replacement) - -namespace llvm { -namespace yaml { - -/// \brief Specialized MappingTraits to describe how a Replacement is -/// (de)serialized. -template <> struct MappingTraits<clang::tooling::Replacement> { - /// \brief Helper to (de)serialize a Replacement since we don't have direct - /// access to its data members. - struct NormalizedReplacement { - NormalizedReplacement(const IO &) - : FilePath(""), Offset(0), Length(0), ReplacementText("") {} - - NormalizedReplacement(const IO &, const clang::tooling::Replacement &R) - : FilePath(R.getFilePath()), Offset(R.getOffset()), - Length(R.getLength()), ReplacementText(R.getReplacementText()) {} - - clang::tooling::Replacement denormalize(const IO &) { - return clang::tooling::Replacement(FilePath, Offset, Length, - ReplacementText); - } - - std::string FilePath; - unsigned int Offset; - unsigned int Length; - std::string ReplacementText; - }; - - static void mapping(IO &Io, clang::tooling::Replacement &R) { - MappingNormalization<NormalizedReplacement, clang::tooling::Replacement> - Keys(Io, R); - Io.mapRequired("FilePath", Keys->FilePath); - Io.mapRequired("Offset", Keys->Offset); - Io.mapRequired("Length", Keys->Length); - Io.mapRequired("ReplacementText", Keys->ReplacementText); - } -}; - -/// \brief Specialized MappingTraits to describe how a -/// TranslationUnitReplacements is (de)serialized. -template <> struct MappingTraits<clang::tooling::TranslationUnitReplacements> { - static void mapping(IO &Io, - clang::tooling::TranslationUnitReplacements &Doc) { - Io.mapRequired("MainSourceFile", Doc.MainSourceFile); - Io.mapOptional("Context", Doc.Context, std::string()); - Io.mapRequired("Replacements", Doc.Replacements); - } -}; -} // end namespace yaml -} // end namespace llvm - -#endif diff --git a/include/clang/Tooling/Tooling.h b/include/clang/Tooling/Tooling.h deleted file mode 100644 index b7a9b25..0000000 --- a/include/clang/Tooling/Tooling.h +++ /dev/null @@ -1,455 +0,0 @@ -//===--- Tooling.h - Framework for standalone Clang tools -------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file implements functions to run clang tools standalone instead -// of running them as a plugin. -// -// A ClangTool is initialized with a CompilationDatabase and a set of files -// to run over. The tool will then run a user-specified FrontendAction over -// all TUs in which the given files are compiled. -// -// It is also possible to run a FrontendAction over a snippet of code by -// calling runToolOnCode, which is useful for unit testing. -// -// Applications that need more fine grained control over how to run -// multiple FrontendActions over code can use ToolInvocation. -// -// Example tools: -// - running clang -fsyntax-only over source code from an editor to get -// fast syntax checks -// - running match/replace tools over C++ code -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLING_TOOLING_H -#define LLVM_CLANG_TOOLING_TOOLING_H - -#include "clang/AST/ASTConsumer.h" -#include "clang/Frontend/PCHContainerOperations.h" -#include "clang/Basic/Diagnostic.h" -#include "clang/Basic/FileManager.h" -#include "clang/Basic/LLVM.h" -#include "clang/Driver/Util.h" -#include "clang/Frontend/FrontendAction.h" -#include "clang/Lex/ModuleLoader.h" -#include "clang/Tooling/ArgumentsAdjusters.h" -#include "clang/Tooling/CompilationDatabase.h" -#include "llvm/ADT/StringMap.h" -#include "llvm/ADT/Twine.h" -#include "llvm/Option/Option.h" -#include <memory> -#include <string> -#include <vector> - -namespace clang { - -namespace driver { -class Compilation; -} // end namespace driver - -class CompilerInvocation; -class SourceManager; -class FrontendAction; - -namespace tooling { - -/// \brief Interface to process a clang::CompilerInvocation. -/// -/// If your tool is based on FrontendAction, you should be deriving from -/// FrontendActionFactory instead. -class ToolAction { -public: - virtual ~ToolAction(); - - /// \brief Perform an action for an invocation. - virtual bool - runInvocation(clang::CompilerInvocation *Invocation, FileManager *Files, - std::shared_ptr<PCHContainerOperations> PCHContainerOps, - DiagnosticConsumer *DiagConsumer) = 0; -}; - -/// \brief Interface to generate clang::FrontendActions. -/// -/// Having a factory interface allows, for example, a new FrontendAction to be -/// created for each translation unit processed by ClangTool. This class is -/// also a ToolAction which uses the FrontendActions created by create() to -/// process each translation unit. -class FrontendActionFactory : public ToolAction { -public: - ~FrontendActionFactory() override; - - /// \brief Invokes the compiler with a FrontendAction created by create(). - bool runInvocation(clang::CompilerInvocation *Invocation, FileManager *Files, - std::shared_ptr<PCHContainerOperations> PCHContainerOps, - DiagnosticConsumer *DiagConsumer) override; - - /// \brief Returns a new clang::FrontendAction. - /// - /// The caller takes ownership of the returned action. - virtual clang::FrontendAction *create() = 0; -}; - -/// \brief Returns a new FrontendActionFactory for a given type. -/// -/// T must derive from clang::FrontendAction. -/// -/// Example: -/// FrontendActionFactory *Factory = -/// newFrontendActionFactory<clang::SyntaxOnlyAction>(); -template <typename T> -std::unique_ptr<FrontendActionFactory> newFrontendActionFactory(); - -/// \brief Callbacks called before and after each source file processed by a -/// FrontendAction created by the FrontedActionFactory returned by \c -/// newFrontendActionFactory. -class SourceFileCallbacks { -public: - virtual ~SourceFileCallbacks() {} - - /// \brief Called before a source file is processed by a FrontEndAction. - /// \see clang::FrontendAction::BeginSourceFileAction - virtual bool handleBeginSource(CompilerInstance &CI, StringRef Filename) { - return true; - } - - /// \brief Called after a source file is processed by a FrontendAction. - /// \see clang::FrontendAction::EndSourceFileAction - virtual void handleEndSource() {} -}; - -/// \brief Returns a new FrontendActionFactory for any type that provides an -/// implementation of newASTConsumer(). -/// -/// FactoryT must implement: ASTConsumer *newASTConsumer(). -/// -/// Example: -/// struct ProvidesASTConsumers { -/// clang::ASTConsumer *newASTConsumer(); -/// } Factory; -/// std::unique_ptr<FrontendActionFactory> FactoryAdapter( -/// newFrontendActionFactory(&Factory)); -template <typename FactoryT> -inline std::unique_ptr<FrontendActionFactory> newFrontendActionFactory( - FactoryT *ConsumerFactory, SourceFileCallbacks *Callbacks = nullptr); - -/// \brief Runs (and deletes) the tool on 'Code' with the -fsyntax-only flag. -/// -/// \param ToolAction The action to run over the code. -/// \param Code C++ code. -/// \param FileName The file name which 'Code' will be mapped as. -/// \param PCHContainerOps The PCHContainerOperations for loading and creating -/// clang modules. -/// -/// \return - True if 'ToolAction' was successfully executed. -bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code, - const Twine &FileName = "input.cc", - std::shared_ptr<PCHContainerOperations> PCHContainerOps = - std::make_shared<PCHContainerOperations>()); - -/// The first part of the pair is the filename, the second part the -/// file-content. -typedef std::vector<std::pair<std::string, std::string>> FileContentMappings; - -/// \brief Runs (and deletes) the tool on 'Code' with the -fsyntax-only flag and -/// with additional other flags. -/// -/// \param ToolAction The action to run over the code. -/// \param Code C++ code. -/// \param Args Additional flags to pass on. -/// \param FileName The file name which 'Code' will be mapped as. -/// \param PCHContainerOps The PCHContainerOperations for loading and creating -/// clang modules. -/// -/// \return - True if 'ToolAction' was successfully executed. -bool runToolOnCodeWithArgs( - clang::FrontendAction *ToolAction, const Twine &Code, - const std::vector<std::string> &Args, const Twine &FileName = "input.cc", - std::shared_ptr<PCHContainerOperations> PCHContainerOps = - std::make_shared<PCHContainerOperations>(), - const FileContentMappings &VirtualMappedFiles = FileContentMappings()); - -/// \brief Builds an AST for 'Code'. -/// -/// \param Code C++ code. -/// \param FileName The file name which 'Code' will be mapped as. -/// \param PCHContainerOps The PCHContainerOperations for loading and creating -/// clang modules. -/// -/// \return The resulting AST or null if an error occurred. -std::unique_ptr<ASTUnit> -buildASTFromCode(const Twine &Code, const Twine &FileName = "input.cc", - std::shared_ptr<PCHContainerOperations> PCHContainerOps = - std::make_shared<PCHContainerOperations>()); - -/// \brief Builds an AST for 'Code' with additional flags. -/// -/// \param Code C++ code. -/// \param Args Additional flags to pass on. -/// \param FileName The file name which 'Code' will be mapped as. -/// \param PCHContainerOps The PCHContainerOperations for loading and creating -/// clang modules. -/// -/// \return The resulting AST or null if an error occurred. -std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs( - const Twine &Code, const std::vector<std::string> &Args, - const Twine &FileName = "input.cc", - std::shared_ptr<PCHContainerOperations> PCHContainerOps = - std::make_shared<PCHContainerOperations>()); - -/// \brief Utility to run a FrontendAction in a single clang invocation. -class ToolInvocation { -public: - /// \brief Create a tool invocation. - /// - /// \param CommandLine The command line arguments to clang. Note that clang - /// uses its binary name (CommandLine[0]) to locate its builtin headers. - /// Callers have to ensure that they are installed in a compatible location - /// (see clang driver implementation) or mapped in via mapVirtualFile. - /// \param FAction The action to be executed. Class takes ownership. - /// \param Files The FileManager used for the execution. Class does not take - /// ownership. - /// \param PCHContainerOps The PCHContainerOperations for loading and creating - /// clang modules. - ToolInvocation(std::vector<std::string> CommandLine, FrontendAction *FAction, - FileManager *Files, - std::shared_ptr<PCHContainerOperations> PCHContainerOps = - std::make_shared<PCHContainerOperations>()); - - /// \brief Create a tool invocation. - /// - /// \param CommandLine The command line arguments to clang. - /// \param Action The action to be executed. - /// \param Files The FileManager used for the execution. - /// \param PCHContainerOps The PCHContainerOperations for loading and creating - /// clang modules. - ToolInvocation(std::vector<std::string> CommandLine, ToolAction *Action, - FileManager *Files, - std::shared_ptr<PCHContainerOperations> PCHContainerOps); - - ~ToolInvocation(); - - /// \brief Set a \c DiagnosticConsumer to use during parsing. - void setDiagnosticConsumer(DiagnosticConsumer *DiagConsumer) { - this->DiagConsumer = DiagConsumer; - } - - /// \brief Map a virtual file to be used while running the tool. - /// - /// \param FilePath The path at which the content will be mapped. - /// \param Content A null terminated buffer of the file's content. - // FIXME: remove this when all users have migrated! - void mapVirtualFile(StringRef FilePath, StringRef Content); - - /// \brief Run the clang invocation. - /// - /// \returns True if there were no errors during execution. - bool run(); - - private: - void addFileMappingsTo(SourceManager &SourceManager); - - bool runInvocation(const char *BinaryName, - clang::driver::Compilation *Compilation, - clang::CompilerInvocation *Invocation, - std::shared_ptr<PCHContainerOperations> PCHContainerOps); - - std::vector<std::string> CommandLine; - ToolAction *Action; - bool OwnsAction; - FileManager *Files; - std::shared_ptr<PCHContainerOperations> PCHContainerOps; - // Maps <file name> -> <file content>. - llvm::StringMap<StringRef> MappedFileContents; - DiagnosticConsumer *DiagConsumer; -}; - -/// \brief Utility to run a FrontendAction over a set of files. -/// -/// This class is written to be usable for command line utilities. -/// By default the class uses ClangSyntaxOnlyAdjuster to modify -/// command line arguments before the arguments are used to run -/// a frontend action. One could install an additional command line -/// arguments adjuster by calling the appendArgumentsAdjuster() method. -class ClangTool { - public: - /// \brief Constructs a clang tool to run over a list of files. - /// - /// \param Compilations The CompilationDatabase which contains the compile - /// command lines for the given source paths. - /// \param SourcePaths The source files to run over. If a source files is - /// not found in Compilations, it is skipped. - /// \param PCHContainerOps The PCHContainerOperations for loading and creating - /// clang modules. - ClangTool(const CompilationDatabase &Compilations, - ArrayRef<std::string> SourcePaths, - std::shared_ptr<PCHContainerOperations> PCHContainerOps = - std::make_shared<PCHContainerOperations>()); - - ~ClangTool(); - - /// \brief Set a \c DiagnosticConsumer to use during parsing. - void setDiagnosticConsumer(DiagnosticConsumer *DiagConsumer) { - this->DiagConsumer = DiagConsumer; - } - - /// \brief Map a virtual file to be used while running the tool. - /// - /// \param FilePath The path at which the content will be mapped. - /// \param Content A null terminated buffer of the file's content. - void mapVirtualFile(StringRef FilePath, StringRef Content); - - /// \brief Append a command line arguments adjuster to the adjuster chain. - /// - /// \param Adjuster An argument adjuster, which will be run on the output of - /// previous argument adjusters. - void appendArgumentsAdjuster(ArgumentsAdjuster Adjuster); - - /// \brief Clear the command line arguments adjuster chain. - void clearArgumentsAdjusters(); - - /// Runs an action over all files specified in the command line. - /// - /// \param Action Tool action. - int run(ToolAction *Action); - - /// \brief Create an AST for each file specified in the command line and - /// append them to ASTs. - int buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs); - - /// \brief Returns the file manager used in the tool. - /// - /// The file manager is shared between all translation units. - FileManager &getFiles() { return *Files; } - - private: - const CompilationDatabase &Compilations; - std::vector<std::string> SourcePaths; - std::shared_ptr<PCHContainerOperations> PCHContainerOps; - - llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem; - llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem; - llvm::IntrusiveRefCntPtr<FileManager> Files; - // Contains a list of pairs (<file name>, <file content>). - std::vector< std::pair<StringRef, StringRef> > MappedFileContents; - llvm::StringSet<> SeenWorkingDirectories; - - ArgumentsAdjuster ArgsAdjuster; - - DiagnosticConsumer *DiagConsumer; -}; - -template <typename T> -std::unique_ptr<FrontendActionFactory> newFrontendActionFactory() { - class SimpleFrontendActionFactory : public FrontendActionFactory { - public: - clang::FrontendAction *create() override { return new T; } - }; - - return std::unique_ptr<FrontendActionFactory>( - new SimpleFrontendActionFactory); -} - -template <typename FactoryT> -inline std::unique_ptr<FrontendActionFactory> newFrontendActionFactory( - FactoryT *ConsumerFactory, SourceFileCallbacks *Callbacks) { - class FrontendActionFactoryAdapter : public FrontendActionFactory { - public: - explicit FrontendActionFactoryAdapter(FactoryT *ConsumerFactory, - SourceFileCallbacks *Callbacks) - : ConsumerFactory(ConsumerFactory), Callbacks(Callbacks) {} - - clang::FrontendAction *create() override { - return new ConsumerFactoryAdaptor(ConsumerFactory, Callbacks); - } - - private: - class ConsumerFactoryAdaptor : public clang::ASTFrontendAction { - public: - ConsumerFactoryAdaptor(FactoryT *ConsumerFactory, - SourceFileCallbacks *Callbacks) - : ConsumerFactory(ConsumerFactory), Callbacks(Callbacks) {} - - std::unique_ptr<clang::ASTConsumer> - CreateASTConsumer(clang::CompilerInstance &, StringRef) override { - return ConsumerFactory->newASTConsumer(); - } - - protected: - bool BeginSourceFileAction(CompilerInstance &CI, - StringRef Filename) override { - if (!clang::ASTFrontendAction::BeginSourceFileAction(CI, Filename)) - return false; - if (Callbacks) - return Callbacks->handleBeginSource(CI, Filename); - return true; - } - void EndSourceFileAction() override { - if (Callbacks) - Callbacks->handleEndSource(); - clang::ASTFrontendAction::EndSourceFileAction(); - } - - private: - FactoryT *ConsumerFactory; - SourceFileCallbacks *Callbacks; - }; - FactoryT *ConsumerFactory; - SourceFileCallbacks *Callbacks; - }; - - return std::unique_ptr<FrontendActionFactory>( - new FrontendActionFactoryAdapter(ConsumerFactory, Callbacks)); -} - -/// \brief Returns the absolute path of \c File, by prepending it with -/// the current directory if \c File is not absolute. -/// -/// Otherwise returns \c File. -/// If 'File' starts with "./", the returned path will not contain the "./". -/// Otherwise, the returned path will contain the literal path-concatenation of -/// the current directory and \c File. -/// -/// The difference to llvm::sys::fs::make_absolute is the canonicalization this -/// does by removing "./" and computing native paths. -/// -/// \param File Either an absolute or relative path. -std::string getAbsolutePath(StringRef File); - -/// \brief Changes CommandLine to contain implicit flags that would have been -/// defined had the compiler driver been invoked through the path InvokedAs. -/// -/// For example, when called with \c InvokedAs set to `i686-linux-android-g++`, -/// the arguments '-target', 'i686-linux-android`, `--driver-mode=g++` will -/// be inserted after the first argument in \c CommandLine. -/// -/// This function will not add new `-target` or `--driver-mode` flags if they -/// are already present in `CommandLine` (even if they have different settings -/// than would have been inserted). -/// -/// \pre `llvm::InitializeAllTargets()` has been called. -/// -/// \param CommandLine the command line used to invoke the compiler driver or -/// Clang tool, including the path to the executable as \c CommandLine[0]. -/// \param InvokedAs the path to the driver used to infer implicit flags. -/// -/// \note This will not set \c CommandLine[0] to \c InvokedAs. The tooling -/// infrastructure expects that CommandLine[0] is a tool path relative to which -/// the builtin headers can be found. -void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine, - StringRef InvokedAs); - -/// \brief Creates a \c CompilerInvocation. -clang::CompilerInvocation *newInvocation( - clang::DiagnosticsEngine *Diagnostics, - const llvm::opt::ArgStringList &CC1Args); - -} // end namespace tooling -} // end namespace clang - -#endif // LLVM_CLANG_TOOLING_TOOLING_H |