diff --git a/CMakeLists.txt b/CMakeLists.txt index 369cc22..a54379c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,59 +1,34 @@ -cmake_minimum_required(VERSION 3.4.3) +cmake_minimum_required(VERSION 3.16) enable_testing() -if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") - # require at least gcc 4.9 !! - if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.9) - message(FATAL_ERROR "GCC version must be at least 4.9!") - endif() -endif() - - -if( CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR ) - project(O2CodeChecker) - - - # find clang + llvm - find_package(Clang REQUIRED) - - if( LLVM_FOUND ) - list(APPEND CMAKE_MODULE_PATH "${LLVM_CMAKE_DIR}") - include(AddLLVM) +project(O2CodeChecker) - # set the compiler flags to match llvm - include(HandleLLVMOptions) - endif() +# find clang + llvm +find_package(Clang REQUIRED CONFIG) - # Make sure that our source directory is on the current cmake module path so that - # we can include cmake files from this directory. - list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules") +if( LLVM_FOUND ) + list(APPEND CMAKE_MODULE_PATH "${LLVM_CMAKE_DIR}") + include(AddLLVM) - # include Clang macros (unfortunately they are not part of the cmake installation) - include(AddClang) + # set the compiler flags to match llvm + include(HandleLLVMOptions) +endif() - # add include directories - include_directories(${LLVM_INCLUDE_DIRS}) +# Make sure that our source directory is on the current cmake module path so that +# we can include cmake files from this directory. +list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules") -set(LLVM_LINK_COMPONENTS - Support - ) +# include Clang macros (unfortunately they are not part of the cmake installation) +include(AddClang) # the main executable add_subdirectory(tool) # the specific aliceO2 checker code add_subdirectory(aliceO2) -# the specific reporting tools code -add_subdirectory(reporting) - -# plugin -add_subdirectory(plugin) # for testing add_subdirectory(test) # some extra utilities add_subdirectory(utility) - - -endif() diff --git a/ClangTidy.h b/ClangTidy.h deleted file mode 100644 index 0ea9a70..0000000 --- a/ClangTidy.h +++ /dev/null @@ -1,259 +0,0 @@ -//===--- ClangTidy.h - clang-tidy -------------------------------*- 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_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDY_H -#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDY_H - -#include "ClangTidyDiagnosticConsumer.h" -#include "ClangTidyOptions.h" -#include "clang/ASTMatchers/ASTMatchFinder.h" -#include "clang/Basic/Diagnostic.h" -#include "clang/Basic/SourceManager.h" -#include "clang/Tooling/Refactoring.h" -#include "llvm/ADT/StringExtras.h" -#include "llvm/Support/raw_ostream.h" -#include -#include -#include - -namespace clang { - -class CompilerInstance; -namespace tooling { -class CompilationDatabase; -} - -namespace tidy { - -/// \brief Provides access to the ``ClangTidyCheck`` options via check-local -/// names. -/// -/// Methods of this class prepend ``CheckName + "."`` to translate check-local -/// option names to global option names. -class OptionsView { -public: - /// \brief Initializes the instance using \p CheckName + "." as a prefix. - OptionsView(StringRef CheckName, - const ClangTidyOptions::OptionMap &CheckOptions); - - /// \brief Read a named option from the ``Context``. - /// - /// Reads the option with the check-local name \p LocalName from the - /// ``CheckOptions``. If the corresponding key is not present, returns - /// \p Default. - std::string get(StringRef LocalName, StringRef Default) const; - - /// \brief Read a named option from the ``Context``. - /// - /// Reads the option with the check-local name \p LocalName from local or - /// global ``CheckOptions``. Gets local option first. If local is not present, - /// falls back to get global option. If global option is not present either, - /// returns Default. - std::string getLocalOrGlobal(StringRef LocalName, StringRef Default) const; - - /// \brief Read a named option from the ``Context`` and parse it as an - /// integral type ``T``. - /// - /// Reads the option with the check-local name \p LocalName from the - /// ``CheckOptions``. If the corresponding key is not present, returns - /// \p Default. - template - typename std::enable_if::value, T>::type - get(StringRef LocalName, T Default) const { - std::string Value = get(LocalName, ""); - T Result = Default; - if (!Value.empty()) - StringRef(Value).getAsInteger(10, Result); - return Result; - } - - /// \brief Read a named option from the ``Context`` and parse it as an - /// integral type ``T``. - /// - /// Reads the option with the check-local name \p LocalName from local or - /// global ``CheckOptions``. Gets local option first. If local is not present, - /// falls back to get global option. If global option is not present either, - /// returns Default. - template - typename std::enable_if::value, T>::type - getLocalOrGlobal(StringRef LocalName, T Default) const { - std::string Value = getLocalOrGlobal(LocalName, ""); - T Result = Default; - if (!Value.empty()) - StringRef(Value).getAsInteger(10, Result); - return Result; - } - - /// \brief Stores an option with the check-local name \p LocalName with string - /// value \p Value to \p Options. - void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, - StringRef Value) const; - - /// \brief Stores an option with the check-local name \p LocalName with - /// ``int64_t`` value \p Value to \p Options. - void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, - int64_t Value) const; - -private: - std::string NamePrefix; - const ClangTidyOptions::OptionMap &CheckOptions; -}; - -/// \brief Base class for all clang-tidy checks. -/// -/// To implement a ``ClangTidyCheck``, write a subclass and override some of the -/// base class's methods. E.g. to implement a check that validates namespace -/// declarations, override ``registerMatchers``: -/// -/// ~~~{.cpp} -/// void registerMatchers(ast_matchers::MatchFinder *Finder) override { -/// Finder->addMatcher(namespaceDecl().bind("namespace"), this); -/// } -/// ~~~ -/// -/// and then override ``check(const MatchResult &Result)`` to do the actual -/// check for each match. -/// -/// A new ``ClangTidyCheck`` instance is created per translation unit. -/// -/// FIXME: Figure out whether carrying information from one TU to another is -/// useful/necessary. -class ClangTidyCheck : public ast_matchers::MatchFinder::MatchCallback { -public: - /// \brief Initializes the check with \p CheckName and \p Context. - /// - /// Derived classes must implement the constructor with this signature or - /// delegate it. If a check needs to read options, it can do this in the - /// constructor using the Options.get() methods below. - ClangTidyCheck(StringRef CheckName, ClangTidyContext *Context) - : CheckName(CheckName), Context(Context), - Options(CheckName, Context->getOptions().CheckOptions) { - assert(Context != nullptr); - assert(!CheckName.empty()); - } - - /// \brief Override this to register ``PPCallbacks`` with ``Compiler``. - /// - /// This should be used for clang-tidy checks that analyze preprocessor- - /// dependent properties, e.g. the order of include directives. - virtual void registerPPCallbacks(CompilerInstance &Compiler) {} - - /// \brief Override this to register AST matchers with \p Finder. - /// - /// This should be used by clang-tidy checks that analyze code properties that - /// dependent on AST knowledge. - /// - /// You can register as many matchers as necessary with \p Finder. Usually, - /// "this" will be used as callback, but you can also specify other callback - /// classes. Thereby, different matchers can trigger different callbacks. - /// - /// If you need to merge information between the different matchers, you can - /// store these as members of the derived class. However, note that all - /// matches occur in the order of the AST traversal. - virtual void registerMatchers(ast_matchers::MatchFinder *Finder) {} - - /// \brief ``ClangTidyChecks`` that register ASTMatchers should do the actual - /// work in here. - virtual void check(const ast_matchers::MatchFinder::MatchResult &Result) {} - - /// \brief Add a diagnostic with the check's name. - DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, - DiagnosticIDs::Level Level = DiagnosticIDs::Warning); - - /// \brief Should store all options supported by this check with their - /// current values or default values for options that haven't been overridden. - /// - /// The check should use ``Options.store()`` to store each option it supports - /// whether it has the default value or it has been overridden. - virtual void storeOptions(ClangTidyOptions::OptionMap &Options) {} - -private: - void run(const ast_matchers::MatchFinder::MatchResult &Result) override; - StringRef getID() const override { return CheckName; } - std::string CheckName; - ClangTidyContext *Context; - -protected: - OptionsView Options; - /// \brief Returns the main file name of the current translation unit. - StringRef getCurrentMainFile() const { return Context->getCurrentFile(); } - /// \brief Returns the language options from the context. - LangOptions getLangOpts() const { return Context->getLangOpts(); } -}; - -class ClangTidyCheckFactories; - -class ClangTidyASTConsumerFactory { -public: - ClangTidyASTConsumerFactory(ClangTidyContext &Context); - - /// \brief Returns an ASTConsumer that runs the specified clang-tidy checks. - std::unique_ptr - CreateASTConsumer(clang::CompilerInstance &Compiler, StringRef File); - - /// \brief Get the list of enabled checks. - std::vector getCheckNames(); - - /// \brief Get the union of options from all checks. - ClangTidyOptions::OptionMap getCheckOptions(); - -private: - ClangTidyContext &Context; - std::unique_ptr CheckFactories; -}; - -/// \brief Fills the list of check names that are enabled when the provided -/// filters are applied. -std::vector getCheckNames(const ClangTidyOptions &Options, - bool AllowEnablingAnalyzerAlphaCheckers); - -/// \brief Returns the effective check-specific options. -/// -/// The method configures ClangTidy with the specified \p Options and collects -/// effective options from all created checks. The returned set of options -/// includes default check-specific options for all keys not overridden by \p -/// Options. -ClangTidyOptions::OptionMap -getCheckOptions(const ClangTidyOptions &Options, - bool AllowEnablingAnalyzerAlphaCheckers); - -/// \brief Run a set of clang-tidy checks on a set of files. -/// -/// \param EnableCheckProfile If provided, it enables check profile collection -/// in MatchFinder, and will contain the result of the profile. -/// \param StoreCheckProfile If provided, and EnableCheckProfile is true, -/// the profile will not be output to stderr, but will instead be stored -/// as a JSON file in the specified directory. -void runClangTidy(clang::tidy::ClangTidyContext &Context, - const tooling::CompilationDatabase &Compilations, - ArrayRef InputFiles, - llvm::IntrusiveRefCntPtr BaseFS, - bool EnableCheckProfile = false, - llvm::StringRef StoreCheckProfile = StringRef()); - -// FIXME: This interface will need to be significantly extended to be useful. -// FIXME: Implement confidence levels for displaying/fixing errors. -// -/// \brief Displays the found \p Errors to the users. If \p Fix is true, \p -/// Errors containing fixes are automatically applied and reformatted. If no -/// clang-format configuration file is found, the given \P FormatStyle is used. -void handleErrors(ClangTidyContext &Context, bool Fix, - unsigned &WarningsAsErrorsCount, - llvm::IntrusiveRefCntPtr BaseFS); - -/// \brief Serializes replacements into YAML and writes them to the specified -/// output stream. -void exportReplacements(StringRef MainFilePath, - const std::vector &Errors, - raw_ostream &OS); - -} // end namespace tidy -} // end namespace clang - -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDY_H diff --git a/ClangTidyDiagnosticConsumer.h b/ClangTidyDiagnosticConsumer.h deleted file mode 100644 index ae25013..0000000 --- a/ClangTidyDiagnosticConsumer.h +++ /dev/null @@ -1,276 +0,0 @@ -//===--- ClangTidyDiagnosticConsumer.h - clang-tidy -------------*- 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_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYDIAGNOSTICCONSUMER_H -#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYDIAGNOSTICCONSUMER_H - -#include "ClangTidyOptions.h" -#include "ClangTidyProfiling.h" -#include "clang/Basic/Diagnostic.h" -#include "clang/Basic/SourceManager.h" -#include "clang/Tooling/Core/Diagnostic.h" -#include "clang/Tooling/Refactoring.h" -#include "llvm/ADT/DenseMap.h" -#include "llvm/ADT/StringMap.h" -#include "llvm/Support/Regex.h" -#include "llvm/Support/Timer.h" - -namespace clang { - -class ASTContext; -class CompilerInstance; -namespace ast_matchers { -class MatchFinder; -} -namespace tooling { -class CompilationDatabase; -} - -namespace tidy { - -/// \brief A detected error complete with information to display diagnostic and -/// automatic fix. -/// -/// This is used as an intermediate format to transport Diagnostics without a -/// dependency on a SourceManager. -/// -/// FIXME: Make Diagnostics flexible enough to support this directly. -struct ClangTidyError : tooling::Diagnostic { - ClangTidyError(StringRef CheckName, Level DiagLevel, StringRef BuildDirectory, - bool IsWarningAsError); - - bool IsWarningAsError; -}; - -/// \brief Read-only set of strings represented as a list of positive and -/// negative globs. Positive globs add all matched strings to the set, negative -/// globs remove them in the order of appearance in the list. -class GlobList { -public: - /// \brief \p GlobList is a comma-separated list of globs (only '*' - /// metacharacter is supported) with optional '-' prefix to denote exclusion. - GlobList(StringRef Globs); - - /// \brief Returns \c true if the pattern matches \p S. The result is the last - /// matching glob's Positive flag. - bool contains(StringRef S) { return contains(S, false); } - -private: - bool contains(StringRef S, bool Contains); - - bool Positive; - llvm::Regex Regex; - std::unique_ptr NextGlob; -}; - -/// \brief Contains displayed and ignored diagnostic counters for a ClangTidy -/// run. -struct ClangTidyStats { - ClangTidyStats() - : ErrorsDisplayed(0), ErrorsIgnoredCheckFilter(0), ErrorsIgnoredNOLINT(0), - ErrorsIgnoredNonUserCode(0), ErrorsIgnoredLineFilter(0) {} - - unsigned ErrorsDisplayed; - unsigned ErrorsIgnoredCheckFilter; - unsigned ErrorsIgnoredNOLINT; - unsigned ErrorsIgnoredNonUserCode; - unsigned ErrorsIgnoredLineFilter; - - unsigned errorsIgnored() const { - return ErrorsIgnoredNOLINT + ErrorsIgnoredCheckFilter + - ErrorsIgnoredNonUserCode + ErrorsIgnoredLineFilter; - } -}; - -/// \brief Every \c ClangTidyCheck reports errors through a \c DiagnosticsEngine -/// provided by this context. -/// -/// A \c ClangTidyCheck always has access to the active context to report -/// warnings like: -/// \code -/// Context->Diag(Loc, "Single-argument constructors must be explicit") -/// << FixItHint::CreateInsertion(Loc, "explicit "); -/// \endcode -class ClangTidyContext { -public: - /// \brief Initializes \c ClangTidyContext instance. - ClangTidyContext(std::unique_ptr OptionsProvider, - bool AllowEnablingAnalyzerAlphaCheckers = false); - - ~ClangTidyContext(); - - /// \brief Report any errors detected using this method. - /// - /// This is still under heavy development and will likely change towards using - /// tablegen'd diagnostic IDs. - /// FIXME: Figure out a way to manage ID spaces. - DiagnosticBuilder diag(StringRef CheckName, SourceLocation Loc, - StringRef Message, - DiagnosticIDs::Level Level = DiagnosticIDs::Warning); - - /// \brief Sets the \c SourceManager of the used \c DiagnosticsEngine. - /// - /// This is called from the \c ClangTidyCheck base class. - void setSourceManager(SourceManager *SourceMgr); - - /// \brief Should be called when starting to process new translation unit. - void setCurrentFile(StringRef File); - - /// \brief Returns the main file name of the current translation unit. - StringRef getCurrentFile() const { return CurrentFile; } - - /// \brief Sets ASTContext for the current translation unit. - void setASTContext(ASTContext *Context); - - /// \brief Gets the language options from the AST context. - const LangOptions &getLangOpts() const { return LangOpts; } - - /// \brief Returns the name of the clang-tidy check which produced this - /// diagnostic ID. - StringRef getCheckName(unsigned DiagnosticID) const; - - /// \brief Returns \c true if the check is enabled for the \c CurrentFile. - /// - /// The \c CurrentFile can be changed using \c setCurrentFile. - bool isCheckEnabled(StringRef CheckName) const; - - /// \brief Returns \c true if the check should be upgraded to error for the - /// \c CurrentFile. - bool treatAsError(StringRef CheckName) const; - - /// \brief Returns global options. - const ClangTidyGlobalOptions &getGlobalOptions() const; - - /// \brief Returns options for \c CurrentFile. - /// - /// The \c CurrentFile can be changed using \c setCurrentFile. - const ClangTidyOptions &getOptions() const; - - /// \brief Returns options for \c File. Does not change or depend on - /// \c CurrentFile. - ClangTidyOptions getOptionsForFile(StringRef File) const; - - /// \brief Returns \c ClangTidyStats containing issued and ignored diagnostic - /// counters. - const ClangTidyStats &getStats() const { return Stats; } - - /// \brief Returns all collected errors. - ArrayRef getErrors() const { return Errors; } - - /// \brief Clears collected errors. - void clearErrors() { Errors.clear(); } - - /// \brief Control profile collection in clang-tidy. - void setEnableProfiling(bool Profile); - bool getEnableProfiling() const { return Profile; } - - /// \brief Control storage of profile date. - void setProfileStoragePrefix(StringRef ProfilePrefix); - llvm::Optional - getProfileStorageParams() const; - - /// \brief Should be called when starting to process new translation unit. - void setCurrentBuildDirectory(StringRef BuildDirectory) { - CurrentBuildDirectory = BuildDirectory; - } - - /// \brief Returns build directory of the current translation unit. - const std::string &getCurrentBuildDirectory() { - return CurrentBuildDirectory; - } - - /// \brief If the experimental alpha checkers from the static analyzer can be - /// enabled. - bool canEnableAnalyzerAlphaCheckers() const { - return AllowEnablingAnalyzerAlphaCheckers; - } - -private: - // Calls setDiagnosticsEngine() and storeError(). - friend class ClangTidyDiagnosticConsumer; - friend class ClangTidyPluginAction; - - /// \brief Sets the \c DiagnosticsEngine so that Diagnostics can be generated - /// correctly. - void setDiagnosticsEngine(DiagnosticsEngine *Engine); - - /// \brief Store an \p Error. - void storeError(const ClangTidyError &Error); - - std::vector Errors; - DiagnosticsEngine *DiagEngine; - std::unique_ptr OptionsProvider; - - std::string CurrentFile; - ClangTidyOptions CurrentOptions; - class CachedGlobList; - std::unique_ptr CheckFilter; - std::unique_ptr WarningAsErrorFilter; - - LangOptions LangOpts; - - ClangTidyStats Stats; - - std::string CurrentBuildDirectory; - - llvm::DenseMap CheckNamesByDiagnosticID; - - bool Profile; - std::string ProfilePrefix; - - bool AllowEnablingAnalyzerAlphaCheckers; -}; - -/// \brief A diagnostic consumer that turns each \c Diagnostic into a -/// \c SourceManager-independent \c ClangTidyError. -// -// FIXME: If we move away from unit-tests, this can be moved to a private -// implementation file. -class ClangTidyDiagnosticConsumer : public DiagnosticConsumer { -public: - ClangTidyDiagnosticConsumer(ClangTidyContext &Ctx, - bool RemoveIncompatibleErrors = true); - - // FIXME: The concept of converting between FixItHints and Replacements is - // more generic and should be pulled out into a more useful Diagnostics - // library. - void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, - const Diagnostic &Info) override; - - /// \brief Flushes the internal diagnostics buffer to the ClangTidyContext. - void finish() override; - -private: - void finalizeLastError(); - - void removeIncompatibleErrors(SmallVectorImpl &Errors) const; - - /// \brief Returns the \c HeaderFilter constructed for the options set in the - /// context. - llvm::Regex *getHeaderFilter(); - - /// \brief Updates \c LastErrorRelatesToUserCode and LastErrorPassesLineFilter - /// according to the diagnostic \p Location. - void checkFilters(SourceLocation Location); - bool passesLineFilter(StringRef FileName, unsigned LineNumber) const; - - ClangTidyContext &Context; - bool RemoveIncompatibleErrors; - std::unique_ptr Diags; - SmallVector Errors; - std::unique_ptr HeaderFilter; - bool LastErrorRelatesToUserCode; - bool LastErrorPassesLineFilter; - bool LastErrorWasIgnored; -}; - -} // end namespace tidy -} // end namespace clang - -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYDIAGNOSTICCONSUMER_H diff --git a/ClangTidyModule.h b/ClangTidyModule.h deleted file mode 100644 index 4721636..0000000 --- a/ClangTidyModule.h +++ /dev/null @@ -1,99 +0,0 @@ -//===--- ClangTidyModule.h - clang-tidy -------------------------*- 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_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYMODULE_H -#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYMODULE_H - -#include "ClangTidy.h" -#include "llvm/ADT/StringRef.h" -#include -#include -#include -#include - -namespace clang { -namespace tidy { - -/// \brief A collection of \c ClangTidyCheckFactory instances. -/// -/// All clang-tidy modules register their check factories with an instance of -/// this object. -class ClangTidyCheckFactories { -public: - typedef std::function - CheckFactory; - - /// \brief Registers check \p Factory with name \p Name. - /// - /// For all checks that have default constructors, use \c registerCheck. - void registerCheckFactory(StringRef Name, CheckFactory Factory); - - /// \brief Registers the \c CheckType with the name \p Name. - /// - /// This method should be used for all \c ClangTidyChecks that don't require - /// constructor parameters. - /// - /// For example, if have a clang-tidy check like: - /// \code - /// class MyTidyCheck : public ClangTidyCheck { - /// void registerMatchers(ast_matchers::MatchFinder *Finder) override { - /// .. - /// } - /// }; - /// \endcode - /// you can register it with: - /// \code - /// class MyModule : public ClangTidyModule { - /// void addCheckFactories(ClangTidyCheckFactories &Factories) override { - /// Factories.registerCheck("myproject-my-check"); - /// } - /// }; - /// \endcode - template void registerCheck(StringRef CheckName) { - registerCheckFactory(CheckName, - [](StringRef Name, ClangTidyContext *Context) { - return new CheckType(Name, Context); - }); - } - - /// \brief Create instances of all checks matching \p CheckRegexString and - /// store them in \p Checks. - /// - /// The caller takes ownership of the return \c ClangTidyChecks. - void createChecks(ClangTidyContext *Context, - std::vector> &Checks); - - typedef std::map FactoryMap; - FactoryMap::const_iterator begin() const { return Factories.begin(); } - FactoryMap::const_iterator end() const { return Factories.end(); } - bool empty() const { return Factories.empty(); } - -private: - FactoryMap Factories; -}; - -/// \brief A clang-tidy module groups a number of \c ClangTidyChecks and gives -/// them a prefixed name. -class ClangTidyModule { -public: - virtual ~ClangTidyModule() {} - - /// \brief Implement this function in order to register all \c CheckFactories - /// belonging to this module. - virtual void addCheckFactories(ClangTidyCheckFactories &CheckFactories) = 0; - - /// \brief Gets default options for checks defined in this module. - virtual ClangTidyOptions getModuleOptions(); -}; - -} // end namespace tidy -} // end namespace clang - -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYMODULE_H diff --git a/ClangTidyModuleRegistry.h b/ClangTidyModuleRegistry.h deleted file mode 100644 index dc44d14..0000000 --- a/ClangTidyModuleRegistry.h +++ /dev/null @@ -1,24 +0,0 @@ -//===--- ClangTidyModuleRegistry.h - clang-tidy -----------------*- 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_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYMODULEREGISTRY_H -#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYMODULEREGISTRY_H - -#include "ClangTidyModule.h" -#include "llvm/Support/Registry.h" - -namespace clang { -namespace tidy { - -typedef llvm::Registry ClangTidyModuleRegistry; - -} // end namespace tidy -} // end namespace clang - -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYMODULEREGISTRY_H diff --git a/ClangTidyOptions.h b/ClangTidyOptions.h deleted file mode 100644 index b2a4ce4..0000000 --- a/ClangTidyOptions.h +++ /dev/null @@ -1,275 +0,0 @@ -//===--- ClangTidyOptions.h - clang-tidy ------------------------*- 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_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYOPTIONS_H -#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYOPTIONS_H - -#include "llvm/ADT/Optional.h" -#include "llvm/ADT/StringMap.h" -#include "llvm/ADT/StringRef.h" -#include "llvm/ADT/IntrusiveRefCntPtr.h" -#include "llvm/Support/ErrorOr.h" -#include "clang/Basic/VirtualFileSystem.h" -#include -#include -#include -#include -#include -#include - -namespace clang { -namespace tidy { - -/// \brief Contains a list of line ranges in a single file. -struct FileFilter { - /// \brief File name. - std::string Name; - - /// \brief LineRange is a pair (inclusive). - typedef std::pair LineRange; - - /// \brief A list of line ranges in this file, for which we show warnings. - std::vector LineRanges; -}; - -/// \brief Global options. These options are neither stored nor read from -/// configuration files. -struct ClangTidyGlobalOptions { - /// \brief Output warnings from certain line ranges of certain files only. - /// If empty, no warnings will be filtered. - std::vector LineFilter; -}; - -/// \brief Contains options for clang-tidy. These options may be read from -/// configuration files, and may be different for different translation units. -struct ClangTidyOptions { - /// \brief These options are used for all settings that haven't been - /// overridden by the \c OptionsProvider. - /// - /// Allow no checks and no headers by default. This method initializes - /// check-specific options by calling \c ClangTidyModule::getModuleOptions() - /// of each registered \c ClangTidyModule. - static ClangTidyOptions getDefaults(); - - /// \brief Creates a new \c ClangTidyOptions instance combined from all fields - /// of this instance overridden by the fields of \p Other that have a value. - ClangTidyOptions mergeWith(const ClangTidyOptions &Other) const; - - /// \brief Checks filter. - llvm::Optional Checks; - - /// \brief WarningsAsErrors filter. - llvm::Optional WarningsAsErrors; - - /// \brief Output warnings from headers matching this filter. Warnings from - /// main files will always be displayed. - llvm::Optional HeaderFilterRegex; - - /// \brief Output warnings from system headers matching \c HeaderFilterRegex. - llvm::Optional SystemHeaders; - - /// \brief Format code around applied fixes with clang-format using this - /// style. - /// - /// Can be one of: - /// * 'none' - don't format code around applied fixes; - /// * 'llvm', 'google', 'mozilla' or other predefined clang-format style - /// names; - /// * 'file' - use the .clang-format file in the closest parent directory of - /// each source file; - /// * '{inline-formatting-style-in-yaml-format}'. - /// - /// See clang-format documentation for more about configuring format style. - llvm::Optional FormatStyle; - - /// \brief Specifies the name or e-mail of the user running clang-tidy. - /// - /// This option is used, for example, to place the correct user name in TODO() - /// comments in the relevant check. - llvm::Optional User; - - typedef std::pair StringPair; - typedef std::map OptionMap; - - /// \brief Key-value mapping used to store check-specific options. - OptionMap CheckOptions; - - typedef std::vector ArgList; - - /// \brief Add extra compilation arguments to the end of the list. - llvm::Optional ExtraArgs; - - /// \brief Add extra compilation arguments to the start of the list. - llvm::Optional ExtraArgsBefore; -}; - -/// \brief Abstract interface for retrieving various ClangTidy options. -class ClangTidyOptionsProvider { -public: - static const char OptionsSourceTypeDefaultBinary[]; - static const char OptionsSourceTypeCheckCommandLineOption[]; - static const char OptionsSourceTypeConfigCommandLineOption[]; - - virtual ~ClangTidyOptionsProvider() {} - - /// \brief Returns global options, which are independent of the file. - virtual const ClangTidyGlobalOptions &getGlobalOptions() = 0; - - /// \brief ClangTidyOptions and its source. - // - /// clang-tidy has 3 types of the sources in order of increasing priority: - /// * clang-tidy binary. - /// * '-config' commandline option or a specific configuration file. If the - /// commandline option is specified, clang-tidy will ignore the - /// configuration file. - /// * '-checks' commandline option. - typedef std::pair OptionsSource; - - /// \brief Returns an ordered vector of OptionsSources, in order of increasing - /// priority. - virtual std::vector - getRawOptions(llvm::StringRef FileName) = 0; - - /// \brief Returns options applying to a specific translation unit with the - /// specified \p FileName. - ClangTidyOptions getOptions(llvm::StringRef FileName); -}; - -/// \brief Implementation of the \c ClangTidyOptionsProvider interface, which -/// returns the same options for all files. -class DefaultOptionsProvider : public ClangTidyOptionsProvider { -public: - DefaultOptionsProvider(const ClangTidyGlobalOptions &GlobalOptions, - const ClangTidyOptions &Options) - : GlobalOptions(GlobalOptions), DefaultOptions(Options) {} - const ClangTidyGlobalOptions &getGlobalOptions() override { - return GlobalOptions; - } - std::vector getRawOptions(llvm::StringRef FileName) override; - -private: - ClangTidyGlobalOptions GlobalOptions; - ClangTidyOptions DefaultOptions; -}; - -/// \brief Implementation of ClangTidyOptions interface, which is used for -/// '-config' command-line option. -class ConfigOptionsProvider : public DefaultOptionsProvider { -public: - ConfigOptionsProvider(const ClangTidyGlobalOptions &GlobalOptions, - const ClangTidyOptions &DefaultOptions, - const ClangTidyOptions &ConfigOptions, - const ClangTidyOptions &OverrideOptions); - std::vector getRawOptions(llvm::StringRef FileName) override; - -private: - ClangTidyOptions ConfigOptions; - ClangTidyOptions OverrideOptions; -}; - -/// \brief Implementation of the \c ClangTidyOptionsProvider interface, which -/// tries to find a configuration file in the closest parent directory of each -/// source file. -/// -/// By default, files named ".clang-tidy" will be considered, and the -/// \c clang::tidy::parseConfiguration function will be used for parsing, but a -/// custom set of configuration file names and parsing functions can be -/// specified using the appropriate constructor. -class FileOptionsProvider : public DefaultOptionsProvider { -public: - // \brief A pair of configuration file base name and a function parsing - // configuration from text in the corresponding format. - typedef std::pair( - llvm::StringRef)>> - ConfigFileHandler; - - /// \brief Configuration file handlers listed in the order of priority. - /// - /// Custom configuration file formats can be supported by constructing the - /// list of handlers and passing it to the appropriate \c FileOptionsProvider - /// constructor. E.g. initialization of a \c FileOptionsProvider with support - /// of a custom configuration file format for files named ".my-tidy-config" - /// could look similar to this: - /// \code - /// FileOptionsProvider::ConfigFileHandlers ConfigHandlers; - /// ConfigHandlers.emplace_back(".my-tidy-config", parseMyConfigFormat); - /// ConfigHandlers.emplace_back(".clang-tidy", parseConfiguration); - /// return llvm::make_unique( - /// GlobalOptions, DefaultOptions, OverrideOptions, ConfigHandlers); - /// \endcode - /// - /// With the order of handlers shown above, the ".my-tidy-config" file would - /// take precedence over ".clang-tidy" if both reside in the same directory. - typedef std::vector ConfigFileHandlers; - - /// \brief Initializes the \c FileOptionsProvider instance. - /// - /// \param GlobalOptions are just stored and returned to the caller of - /// \c getGlobalOptions. - /// - /// \param DefaultOptions are used for all settings not specified in a - /// configuration file. - /// - /// If any of the \param OverrideOptions fields are set, they will override - /// whatever options are read from the configuration file. - FileOptionsProvider(const ClangTidyGlobalOptions &GlobalOptions, - const ClangTidyOptions &DefaultOptions, - const ClangTidyOptions &OverrideOptions, - llvm::IntrusiveRefCntPtr FS = nullptr); - - /// \brief Initializes the \c FileOptionsProvider instance with a custom set - /// of configuration file handlers. - /// - /// \param GlobalOptions are just stored and returned to the caller of - /// \c getGlobalOptions. - /// - /// \param DefaultOptions are used for all settings not specified in a - /// configuration file. - /// - /// If any of the \param OverrideOptions fields are set, they will override - /// whatever options are read from the configuration file. - /// - /// \param ConfigHandlers specifies a custom set of configuration file - /// handlers. Each handler is a pair of configuration file name and a function - /// that can parse configuration from this file type. The configuration files - /// in each directory are searched for in the order of appearance in - /// \p ConfigHandlers. - FileOptionsProvider(const ClangTidyGlobalOptions &GlobalOptions, - const ClangTidyOptions &DefaultOptions, - const ClangTidyOptions &OverrideOptions, - const ConfigFileHandlers &ConfigHandlers); - - std::vector getRawOptions(llvm::StringRef FileName) override; - -protected: - /// \brief Try to read configuration files from \p Directory using registered - /// \c ConfigHandlers. - llvm::Optional tryReadConfigFile(llvm::StringRef Directory); - - llvm::StringMap CachedOptions; - ClangTidyOptions OverrideOptions; - ConfigFileHandlers ConfigHandlers; - llvm::IntrusiveRefCntPtr FS; -}; - -/// \brief Parses LineFilter from JSON and stores it to the \p Options. -std::error_code parseLineFilter(llvm::StringRef LineFilter, - ClangTidyGlobalOptions &Options); - -/// \brief Parses configuration from JSON and returns \c ClangTidyOptions or an -/// error. -llvm::ErrorOr parseConfiguration(llvm::StringRef Config); - -/// \brief Serializes configuration to a YAML-encoded string. -std::string configurationAsText(const ClangTidyOptions &Options); - -} // end namespace tidy -} // end namespace clang - -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYOPTIONS_H diff --git a/ClangTidyProfiling.h b/ClangTidyProfiling.h deleted file mode 100644 index 9d86b8e..0000000 --- a/ClangTidyProfiling.h +++ /dev/null @@ -1,60 +0,0 @@ -//===--- ClangTidyProfiling.h - clang-tidy ----------------------*- 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_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYPROFILING_H -#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYPROFILING_H - -#include "llvm/ADT/Optional.h" -#include "llvm/ADT/StringMap.h" -#include "llvm/Support/Chrono.h" -#include "llvm/Support/Timer.h" -#include "llvm/Support/raw_ostream.h" -#include -#include -#include - -namespace clang { -namespace tidy { - -class ClangTidyProfiling { -public: - struct StorageParams { - llvm::sys::TimePoint<> Timestamp; - std::string SourceFilename; - std::string StoreFilename; - - StorageParams() = default; - - StorageParams(llvm::StringRef ProfilePrefix, llvm::StringRef SourceFile); - }; - -private: - llvm::Optional TG; - - llvm::Optional Storage; - - void printUserFriendlyTable(llvm::raw_ostream &OS); - void printAsJSON(llvm::raw_ostream &OS); - - void storeProfileData(); - -public: - llvm::StringMap Records; - - ClangTidyProfiling() = default; - - ClangTidyProfiling(llvm::Optional Storage); - - ~ClangTidyProfiling(); -}; - -} // end namespace tidy -} // end namespace clang - -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYPROFILING_H diff --git a/README.md b/README.md index fb8e067..358de1e 100644 --- a/README.md +++ b/README.md @@ -15,4 +15,4 @@ It offers: In the build directory of AliceO2 (containing the CMake compilations database in form of `compile_command.json`), run - run_O2CodeChecker.py -clang-tidy-binary `which O2codecheck` -checks=-*,alice* + run_O2CodeChecker.py -clang-tidy-binary `which O2codecheck` -checks=*,alice* diff --git a/aliceO2/AliceO2TidyModule.cpp b/aliceO2/AliceO2TidyModule.cpp index a8d79da..71f5ac1 100644 --- a/aliceO2/AliceO2TidyModule.cpp +++ b/aliceO2/AliceO2TidyModule.cpp @@ -7,9 +7,9 @@ // //===----------------------------------------------------------------------===// -#include "../ClangTidy.h" -#include "../ClangTidyModule.h" -#include "../ClangTidyModuleRegistry.h" +#include "clang-tidy/ClangTidy.h" +#include "clang-tidy/ClangTidyModule.h" +#include "clang-tidy/ClangTidyModuleRegistry.h" #include "MemberNamesCheck.h" #include "NamespaceNamingCheck.h" #include "SizeofCheck.h" diff --git a/aliceO2/CMakeLists.txt b/aliceO2/CMakeLists.txt index 0c487da..e00c918 100644 --- a/aliceO2/CMakeLists.txt +++ b/aliceO2/CMakeLists.txt @@ -1,17 +1,16 @@ -set(LLVM_LINK_COMPONENTS support) +add_library(clangTidyAliceO2Module MODULE "") +target_compile_options(clangTidyAliceO2Module PRIVATE -fno-rtti) +target_include_directories(clangTidyAliceO2Module + PRIVATE + ${CLANG_INCLUDE_DIRS} + ${LLVM_INCLUDE_DIRS} +) -add_clang_library(clangTidyAliceO2Module - AliceO2TidyModule.cpp - MemberNamesCheck.cpp - NamespaceNamingCheck.cpp - SizeofCheck.cpp - - LINK_LIBS - clangAST - clangASTMatchers - clangBasic - clangLex - clangTidy - clangTidyUtils - clangTooling - ) +target_sources(clangTidyAliceO2Module + PRIVATE + ${CMAKE_CURRENT_LIST_DIR}/AliceO2TidyModule.cpp + ${CMAKE_CURRENT_LIST_DIR}/MemberNamesCheck.cpp + ${CMAKE_CURRENT_LIST_DIR}/NamespaceNamingCheck.cpp + ${CMAKE_CURRENT_LIST_DIR}/SizeofCheck.cpp +) +install(TARGETS clangTidyAliceO2Module LIBRARY DESTINATION lib) diff --git a/aliceO2/MemberNamesCheck.h b/aliceO2/MemberNamesCheck.h index 2c48e4e..1785110 100644 --- a/aliceO2/MemberNamesCheck.h +++ b/aliceO2/MemberNamesCheck.h @@ -10,7 +10,8 @@ #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ALICEO2_MEMBER_NAMES_H #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ALICEO2_MEMBER_NAMES_H -#include "../ClangTidy.h" +#include "clang-tidy/ClangTidy.h" +#include "clang-tidy/ClangTidyCheck.h" #include namespace clang { diff --git a/aliceO2/NamespaceNamingCheck.cpp b/aliceO2/NamespaceNamingCheck.cpp index 3f020dd..ca9790a 100644 --- a/aliceO2/NamespaceNamingCheck.cpp +++ b/aliceO2/NamespaceNamingCheck.cpp @@ -9,6 +9,7 @@ #include "NamespaceNamingCheck.h" #include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchersMacros.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include #include @@ -17,6 +18,13 @@ using namespace clang::ast_matchers; namespace clang { +namespace ast_matchers { +AST_MATCHER_P(UsingDirectiveDecl, nominatedNamespace, + internal::Matcher, InnerMatcher) +{ + return InnerMatcher.matches(*Node.getNominatedNamespace(), Finder, Builder); +} +} // namespace ast_matchers namespace tidy { namespace aliceO2 { @@ -42,18 +50,26 @@ bool isOutsideOfTargetScope(std::string filename) void NamespaceNamingCheck::registerMatchers(MatchFinder *Finder) { const auto validNameMatch = matchesName( std::string("::") + VALID_NAME_REGEX + "$" ); + const auto inO2NSMatch = matchesName("^::o2::"); // matches namespace declarations that have invalid name Finder->addMatcher(namespaceDecl(allOf( + inO2NSMatch, unless(validNameMatch), unless(isAnonymous()) )).bind("namespace-decl"), this); // matches usage of namespace - Finder->addMatcher(nestedNameSpecifierLoc(loc(nestedNameSpecifier(specifiesNamespace(unless(validNameMatch) - )))).bind("namespace-usage"), this ); + Finder->addMatcher(nestedNameSpecifierLoc(loc(nestedNameSpecifier(specifiesNamespace(allOf( + inO2NSMatch, + unless(validNameMatch) + ))))).bind("namespace-usage"), this); // matches "using namespace" declarations - Finder->addMatcher(usingDirectiveDecl(unless(isImplicit() - )).bind("using-namespace"), this); + Finder->addMatcher(usingDirectiveDecl(allOf( + unless(isImplicit()), + nominatedNamespace(allOf( + inO2NSMatch, + unless(validNameMatch) + )))).bind("using-namespace"), this); } void NamespaceNamingCheck::check(const MatchFinder::MatchResult &Result) { @@ -69,7 +85,7 @@ void NamespaceNamingCheck::check(const MatchFinder::MatchResult &Result) { if(fixNamespaceName(newName)) { - diag(MatchedNamespaceDecl->getLocation(), "namespace %0 does not follow the underscore convention") + diag(MatchedNamespaceDecl->getLocation(), "namespace %q0 does not follow the underscore convention") << MatchedNamespaceDecl << FixItHint::CreateReplacement(MatchedNamespaceDecl->getLocation(), newName); } @@ -92,7 +108,7 @@ void NamespaceNamingCheck::check(const MatchFinder::MatchResult &Result) { if(fixNamespaceName(newName)) { - diag(MatchedNamespaceLoc->getLocalBeginLoc(), "namespace %0 does not follow the underscore convention") + diag(MatchedNamespaceLoc->getLocalBeginLoc(), "namespace %q0 does not follow the underscore convention") << AsNamespace << FixItHint::CreateReplacement(MatchedNamespaceLoc->getLocalBeginLoc(), newName); } @@ -112,14 +128,9 @@ void NamespaceNamingCheck::check(const MatchFinder::MatchResult &Result) { std::string newName(MatchedUsingNamespace->getNominatedNamespace()->getDeclName().getAsString()); std::string oldName=newName; - if( std::regex_match(newName, std::regex(VALID_NAME_REGEX)) ) - { - return; - } - if(fixNamespaceName(newName)) { - diag(MatchedUsingNamespace->getLocation(), "namespace %0 does not follow the underscore convention") + diag(MatchedUsingNamespace->getLocation(), "namespace %q0 does not follow the underscore convention") << MatchedUsingNamespace->getNominatedNamespace() << FixItHint::CreateReplacement(MatchedUsingNamespace->getLocation(), newName); } @@ -132,7 +143,7 @@ void NamespaceNamingCheck::check(const MatchFinder::MatchResult &Result) { bool NamespaceNamingCheck::fixNamespaceName(std::string &name) { - std::string replace_option = Options.get(name, ""); + std::string replace_option = Options.get(name, "").str(); if( replace_option != "" ) { name = replace_option; diff --git a/aliceO2/NamespaceNamingCheck.h b/aliceO2/NamespaceNamingCheck.h index e931dc9..b5c08fc 100644 --- a/aliceO2/NamespaceNamingCheck.h +++ b/aliceO2/NamespaceNamingCheck.h @@ -10,7 +10,8 @@ #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ALICEO2_NAMESPACE_NAMING_H #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ALICEO2_NAMESPACE_NAMING_H -#include "../ClangTidy.h" +#include "clang-tidy/ClangTidy.h" +#include "clang-tidy/ClangTidyCheck.h" namespace clang { namespace tidy { diff --git a/aliceO2/SizeofCheck.cpp b/aliceO2/SizeofCheck.cpp index bd2c24e..da8d2e0 100644 --- a/aliceO2/SizeofCheck.cpp +++ b/aliceO2/SizeofCheck.cpp @@ -31,7 +31,7 @@ void SizeofCheck::check(const MatchFinder::MatchResult &Result) { // is argument of sizeof a Type? if (Expr->isArgumentType()) { - diag(Expr->getLocStart(), "consider using sizeof() on instance instead on direct type"); + diag(Expr->getBeginLoc(), "consider using sizeof() on instance instead on direct type"); return; } @@ -41,7 +41,7 @@ void SizeofCheck::check(const MatchFinder::MatchResult &Result) { } // no parens -> issue warning - diag(Expr->getLocStart(), "consider using parens () for arguments to sizeof"); + diag(Expr->getBeginLoc(), "consider using parens () for arguments to sizeof"); } } // namespace aliceO2 diff --git a/aliceO2/SizeofCheck.h b/aliceO2/SizeofCheck.h index 8abd8e3..7a02883 100644 --- a/aliceO2/SizeofCheck.h +++ b/aliceO2/SizeofCheck.h @@ -10,7 +10,8 @@ #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ALICEO2_SIZEOF_H #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ALICEO2_SIZEOF_H -#include "../ClangTidy.h" +#include "clang-tidy/ClangTidy.h" +#include "clang-tidy/ClangTidyCheck.h" namespace clang { namespace tidy { diff --git a/plugin/CMakeLists.txt b/plugin/CMakeLists.txt deleted file mode 100644 index 942142d..0000000 --- a/plugin/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -set(LLVM_LINK_COMPONENTS support) - -add_clang_library(clangTidyPluginModule - SHARED - - FooCheck.cpp - PluginTidyModule.cpp - - LINK_LIBS - clangAST - clangASTMatchers - clangBasic - clangLex - clangTidy - clangTidyUtils - clangTooling - ) diff --git a/plugin/FooCheck.cpp b/plugin/FooCheck.cpp deleted file mode 100644 index cd8cc9d..0000000 --- a/plugin/FooCheck.cpp +++ /dev/null @@ -1,34 +0,0 @@ -//===--- FooCheck.cpp - clang-tidy-----------------------------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "FooCheck.h" -#include "clang/AST/ASTContext.h" -#include "clang/ASTMatchers/ASTMatchFinder.h" - -using namespace clang::ast_matchers; - -namespace clang { -namespace tidy { -namespace plugin { - -void FooCheck::registerMatchers(MatchFinder *Finder) { - // FIXME: Add matchers. - Finder->addMatcher(functionDecl().bind("x"), this); -} - -void FooCheck::check(const MatchFinder::MatchResult &Result) { - // FIXME: Add callback implementation. - const auto *MatchedDecl = Result.Nodes.getNodeAs("x"); - diag(MatchedDecl->getLocation(), "you should not use functions") - << MatchedDecl; -} - -} // namespace plugin -} // namespace tidy -} // namespace clang diff --git a/plugin/FooCheck.h b/plugin/FooCheck.h deleted file mode 100644 index 042bd19..0000000 --- a/plugin/FooCheck.h +++ /dev/null @@ -1,35 +0,0 @@ -//===--- FooCheck.h - clang-tidy---------------------------------*- 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_TOOLS_EXTRA_CLANG_TIDY_PLUGIN_FOO_H -#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PLUGIN_FOO_H - -#include "../ClangTidy.h" - -namespace clang { -namespace tidy { -namespace plugin { - -/// FIXME: Write a short description. -/// -/// For the user-facing documentation see: -/// http://clang.llvm.org/extra/clang-tidy/checks/plugin-Foo.html -class FooCheck : public ClangTidyCheck { -public: - FooCheck(StringRef Name, ClangTidyContext *Context) - : ClangTidyCheck(Name, Context) {} - void registerMatchers(ast_matchers::MatchFinder *Finder) override; - void check(const ast_matchers::MatchFinder::MatchResult &Result) override; -}; - -} // namespace plugin -} // namespace tidy -} // namespace clang - -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PLUGIN_FOO_H diff --git a/plugin/PluginTidyModule.cpp b/plugin/PluginTidyModule.cpp deleted file mode 100644 index 20a726e..0000000 --- a/plugin/PluginTidyModule.cpp +++ /dev/null @@ -1,48 +0,0 @@ -//===--- PluginTidyModule.cpp - clang-tidy ----------------------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "../ClangTidy.h" -#include "../ClangTidyModule.h" -#include "../ClangTidyModuleRegistry.h" -#include "FooCheck.h" -#include - -namespace clang { -namespace tidy { -namespace plugin { - -class PluginModule : public ClangTidyModule { -public: - void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override { - std::cerr << "side effect \n"; - CheckFactories.registerCheck( - "plugin-Foo"); - } -}; - -} // namespace plugin - -// Register the PluginTidyModule using this statically initialized variable. -static ClangTidyModuleRegistry::Add -X("pluginO2-module", "Adds Plugin specific checks"); - -// This anchor is used to force the linker to link in the generated object file -// and thus register the PluginModule. -volatile int PluginModuleAnchorSource = 0; - -} // namespace tidy -} // namespace clang - - -// A function to execute upon load of shared library -//__attribute__((constructor)) -static int huhuhuhuhu() { - static clang::tidy::plugin::PluginModule module; - return clang::tidy::PluginModuleAnchorSource; -} diff --git a/reporting/CMakeLists.txt b/reporting/CMakeLists.txt deleted file mode 100644 index e41a910..0000000 --- a/reporting/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -set(LLVM_LINK_COMPONENTS support) - -add_clang_library(clangTidyReportingModule - ReportingTidyModule.cpp - InterfaceLister.cpp - VirtFuncLister.cpp - - LINK_LIBS - clangAST - clangASTMatchers - clangBasic - clangLex - clangTidy - clangTidyUtils - clangTooling - ) diff --git a/reporting/InterfaceLister.cpp b/reporting/InterfaceLister.cpp deleted file mode 100644 index cfe0638..0000000 --- a/reporting/InterfaceLister.cpp +++ /dev/null @@ -1,46 +0,0 @@ -//===--- InterfaceLister.cpp - clang-tidy---------------------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "InterfaceLister.h" -#include "clang/AST/ASTContext.h" -#include "clang/ASTMatchers/ASTMatchFinder.h" -#include - -using namespace clang::ast_matchers; - -namespace clang { -namespace tidy { -namespace reporting { - -void InterfaceLister::registerMatchers(MatchFinder *Finder) { - Finder->addMatcher(cxxMemberCallExpr().bind("member"), this); -} - -void InterfaceLister::check(const MatchFinder::MatchResult &Result) { - const auto *MatchedCallExpr = - Result.Nodes.getNodeAs("member"); - if (MatchedCallExpr) { - if (std::strcmp(MatchedCallExpr->getRecordDecl() - ->getDeclName() - .getAsString() - .c_str(), - ClassName.c_str()) != 0) - return; - - std::string sourceInfo(MatchedCallExpr->getExprLoc().printToString( - *Result.SourceManager)); - std::cerr << sourceInfo << " ; " << ClassName << " : " - << MatchedCallExpr->getMethodDecl()->getQualifiedNameAsString() - << "\n"; - } -} - -} // namespace reporting -} // namespace tidy -} // namespace clang diff --git a/reporting/InterfaceLister.h b/reporting/InterfaceLister.h deleted file mode 100644 index c2e0a47..0000000 --- a/reporting/InterfaceLister.h +++ /dev/null @@ -1,42 +0,0 @@ -//===--- MemberNamesCheck.h - clang-tidy-------------------------*- 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_TOOLS_EXTRA_CLANG_TIDY_INTERFACELISTER_NAMES_H -#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_INTERFACELISTER_NAMES_H - -#include "../ClangTidy.h" - -namespace clang { -namespace tidy { -namespace reporting { - -/// A simple tool/check that given a ClassName reports the interfaces -/// used in the code base -/// -class InterfaceLister : public ClangTidyCheck { -private: - const std::string ClassName; // the class name for which we want to find - // used interfaces -public: - InterfaceLister(StringRef Name, ClangTidyContext *Context) - : ClangTidyCheck(Name, Context), ClassName(Options.get("ClassName", "")) {} - - void storeOptions(ClangTidyOptions::OptionMap &Opts) override { - Options.store(Opts, "ClassName", ClassName); - } - - void registerMatchers(ast_matchers::MatchFinder *Finder) override; - void check(const ast_matchers::MatchFinder::MatchResult &Result) override; -}; - -} // namespace reporting -} // namespace tidy -} // namespace clang - -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_INTERFACELISTER_NAMES_H diff --git a/reporting/ReportingTidyModule.cpp b/reporting/ReportingTidyModule.cpp deleted file mode 100644 index adf1f7d..0000000 --- a/reporting/ReportingTidyModule.cpp +++ /dev/null @@ -1,40 +0,0 @@ -//===--- AliceO2TidyModule.cpp - clang-tidy ----------------------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "../ClangTidy.h" -#include "../ClangTidyModule.h" -#include "../ClangTidyModuleRegistry.h" -#include "InterfaceLister.h" -#include "VirtFuncLister.h" - -namespace clang { -namespace tidy { -namespace reporting { - -class ReportingModule : public ClangTidyModule { -public: - void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override { - CheckFactories.registerCheck("Reporting-interfaces-used"); - - CheckFactories.registerCheck("Reporting-unusedvirtfunc"); - } -}; - -} // namespace Reporting - -// Register the ReportingTidyModule using this statically initialized variable. -static ClangTidyModuleRegistry::Add -X("Reporting-module", "Adds Reporting tools (for simple analytics)"); - -// This anchor is used to force the linker to link in the generated object file -// and thus register the ReportingModule. -volatile int ReportingModuleAnchorSource = 0; - -} // namespace tidy -} // namespace clang diff --git a/reporting/VirtFuncLister.cpp b/reporting/VirtFuncLister.cpp deleted file mode 100644 index deeee11..0000000 --- a/reporting/VirtFuncLister.cpp +++ /dev/null @@ -1,85 +0,0 @@ -//===--- VirtFuncLister.cpp - clang-tidy---------------------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "VirtFuncLister.h" -#include "clang/AST/ASTContext.h" -#include "clang/ASTMatchers/ASTMatchFinder.h" -#include - -using namespace clang::ast_matchers; - -namespace clang { -namespace tidy { -namespace reporting { - -void VirtFuncLister::registerMatchers(MatchFinder *Finder) { - Finder->addMatcher(cxxMethodDecl().bind("method"), this); -} - -void VirtFuncLister::check(const MatchFinder::MatchResult &Result) { - const auto &SM = *Result.SourceManager; - const auto *MatchedDecl = - Result.Nodes.getNodeAs("method"); - if (MatchedDecl) { - DeclarationNameInfo name_info = MatchedDecl->getNameInfo(); - std::string func_name = name_info.getAsString(); - - bool isvirtual = MatchedDecl->isVirtual(); - - llvm::errs() << "MEMBER FUNCTION DECL " << func_name << "("<isVirtualAsWritten() << " is virtual " - << isvirtual << "\n"; - - // get class declaration of this member function - // auto record = MatchedDecl->getCanonicalDecl()->getParent(); - - // we need to get source location the base node - // as well as overriding node - if (isvirtual) { - auto iter = MatchedDecl->begin_overridden_methods(); - auto enditer = MatchedDecl->end_overridden_methods(); - - if (iter == enditer) { - SourceLocation loc = MatchedDecl->getLocStart();//getLocation(); - loc.dump(SM); - llvm::errs() << "VIRTUAL-START-DECLARATION \n"; - } else { - // otherwise find the base this is referring to - decltype(iter) lastiter = iter; - while (iter != enditer) { - lastiter = iter; - // counter number of paths up; if there is more than one - // we have to give up for the moment - int counter = 0; - decltype(iter) countiter = iter; - for (; countiter != enditer; ++countiter) { - counter++; - } - if (counter > 1) { - llvm::errs() << " OVERRIDING MULTIPLE FUNCTIONS NOT TREATED YET\n"; - return; - } - enditer = (*iter)->end_overridden_methods(); - iter = (*iter)->begin_overridden_methods(); - } - SourceLocation loc = (*lastiter)->getLocStart();//getLocation(); - loc.dump(SM); - llvm::errs() << " OVERRIDEN-AT "; - loc = MatchedDecl->getLocStart();//getLocation(); - loc.dump(SM); - llvm::errs() << "\n"; - } - } - } -} - -} // namespace reporting -} // namespace tidy -} // namespace clang diff --git a/reporting/VirtFuncLister.h b/reporting/VirtFuncLister.h deleted file mode 100644 index b71cfe1..0000000 --- a/reporting/VirtFuncLister.h +++ /dev/null @@ -1,35 +0,0 @@ -//===--- MemberNamesCheck.h - clang-tidy-------------------------*- 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_TOOLS_EXTRA_CLANG_TIDY_VIRTFUNCLISTER_NAMES_H -#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_VIRTFUNCLISTER_NAMES_H - -#include "../ClangTidy.h" - -namespace clang { -namespace tidy { -namespace reporting { - -/// A simple tool/check that given a ClassName reports the interfaces -/// used in the code base -/// -class VirtFuncLister : public ClangTidyCheck { -public: - VirtFuncLister(StringRef Name, ClangTidyContext *Context) - : ClangTidyCheck(Name, Context) {} - - void registerMatchers(ast_matchers::MatchFinder *Finder) override; - void check(const ast_matchers::MatchFinder::MatchResult &Result) override; -}; - -} // namespace reporting -} // namespace tidy -} // namespace clang - -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_VIRTFUNCLISTER_NAMES_H diff --git a/tool/CMakeLists.txt b/tool/CMakeLists.txt index c9d9ac9..ae6622f 100644 --- a/tool/CMakeLists.txt +++ b/tool/CMakeLists.txt @@ -1,63 +1 @@ -set(LLVM_LINK_COMPONENTS - AllTargetsAsmParsers - AllTargetsDescs - AllTargetsInfos - support - ) - -add_clang_executable(O2codecheck - ClangTidyMain.cpp - ) - -target_link_libraries(O2codecheck - PRIVATE - clangAST - clangASTMatchers - clangBasic - clangTidy - - # link our own checks - clangTidyAliceO2Module - clangTidyReportingModule - - # include checkers available from main clang-tidy - clangTidyAndroidModule - clangTidyAbseilModule - clangTidyBoostModule - clangTidyBugproneModule - clangTidyCERTModule - clangTidyCppCoreGuidelinesModule - clangTidyFuchsiaModule - clangTidyGoogleModule - clangTidyHICPPModule - clangTidyLLVMModule - clangTidyMiscModule - clangTidyModernizeModule - clangTidyMPIModule - clangTidyObjCModule - clangTidyPerformanceModule - clangTidyPortabilityModule - clangTidyReadabilityModule - clangTidyZirconModule - clangTooling - clangToolingCore - ) - -install(TARGETS O2codecheck - RUNTIME DESTINATION bin) - -#install(PROGRAMS clang-tidy-diff.py DESTINATION share/clang) install(PROGRAMS run_O2CodeChecker.py DESTINATION bin) - -# we need to install the builtin headers in a path which is searched by the tool -# FIXME: a soft link would be better -install(DIRECTORY ${LLVM_LIBRARY_DIR}/clang/${LLVM_PACKAGE_VERSION}/include DESTINATION lib/clang/${LLVM_PACKAGE_VERSION}) - -IF(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") - # On MacOS we need to do the same with C++ headers since they are in a non-standard location - # (alternative would be to set the CPATH environment variable) - INSTALL(CODE "execute_process(COMMAND mkdir ${CMAKE_INSTALL_PREFIX}/include)") - INSTALL(CODE "execute_process(COMMAND ln -sf \ - /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++ \ - ${CMAKE_INSTALL_PREFIX}/include/c++)") -ENDIF() diff --git a/tool/ClangTidyMain.cpp b/tool/ClangTidyMain.cpp deleted file mode 100644 index 11a04f7..0000000 --- a/tool/ClangTidyMain.cpp +++ /dev/null @@ -1,587 +0,0 @@ -//===--- tools/extra/clang-tidy/ClangTidyMain.cpp - Clang tidy tool -------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -/// -/// \file This file implements a clang-tidy tool. -/// -/// This tool uses the Clang Tooling infrastructure, see -/// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html -/// for details on setting it up with LLVM source tree. -/// -//===----------------------------------------------------------------------===// - -#include "../ClangTidy.h" -#include "clang/Tooling/CommonOptionsParser.h" -#include "llvm/Support/Process.h" -#include "llvm/Support/TargetSelect.h" - -using namespace clang::ast_matchers; -using namespace clang::driver; -using namespace clang::tooling; -using namespace llvm; - -static cl::OptionCategory ClangTidyCategory("clang-tidy options"); - -static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); -static cl::extrahelp ClangTidyHelp(R"( -Configuration files: - clang-tidy attempts to read configuration for each source file from a - .clang-tidy file located in the closest parent directory of the source - file. If any configuration options have a corresponding command-line - option, command-line option takes precedence. The effective - configuration can be inspected using -dump-config: - - $ clang-tidy -dump-config - --- - Checks: '-*,some-check' - WarningsAsErrors: '' - HeaderFilterRegex: '' - FormatStyle: none - User: user - CheckOptions: - - key: some-check.SomeOption - value: 'some value' - ... - -)"); - -const char DefaultChecks[] = // Enable these checks by default: - "clang-diagnostic-*," // * compiler diagnostics - "clang-analyzer-*"; // * Static Analyzer checks - -static cl::opt Checks("checks", cl::desc(R"( -Comma-separated list of globs with optional '-' -prefix. Globs are processed in order of -appearance in the list. Globs without '-' -prefix add checks with matching names to the -set, globs with the '-' prefix remove checks -with matching names from the set of enabled -checks. This option's value is appended to the -value of the 'Checks' option in .clang-tidy -file, if any. -)"), - cl::init(""), cl::cat(ClangTidyCategory)); - -static cl::opt WarningsAsErrors("warnings-as-errors", cl::desc(R"( -Upgrades warnings to errors. Same format as -'-checks'. -This option's value is appended to the value of -the 'WarningsAsErrors' option in .clang-tidy -file, if any. -)"), - cl::init(""), - cl::cat(ClangTidyCategory)); - -static cl::opt HeaderFilter("header-filter", cl::desc(R"( -Regular expression matching the names of the -headers to output diagnostics from. Diagnostics -from the main file of each translation unit are -always displayed. -Can be used together with -line-filter. -This option overrides the 'HeaderFilter' option -in .clang-tidy file, if any. -)"), - cl::init(""), - cl::cat(ClangTidyCategory)); - -static cl::opt - SystemHeaders("system-headers", - cl::desc("Display the errors from system headers."), - cl::init(false), cl::cat(ClangTidyCategory)); -static cl::opt LineFilter("line-filter", cl::desc(R"( -List of files with line ranges to filter the -warnings. Can be used together with --header-filter. The format of the list is a -JSON array of objects: - [ - {"name":"file1.cpp","lines":[[1,3],[5,7]]}, - {"name":"file2.h"} - ] -)"), - cl::init(""), - cl::cat(ClangTidyCategory)); - -static cl::opt Fix("fix", cl::desc(R"( -Apply suggested fixes. Without -fix-errors -clang-tidy will bail out if any compilation -errors were found. -)"), - cl::init(false), cl::cat(ClangTidyCategory)); - -static cl::opt FixErrors("fix-errors", cl::desc(R"( -Apply suggested fixes even if compilation -errors were found. If compiler errors have -attached fix-its, clang-tidy will apply them as -well. -)"), - cl::init(false), cl::cat(ClangTidyCategory)); - -static cl::opt FormatStyle("format-style", cl::desc(R"( -Style for formatting code around applied fixes: - - 'none' (default) turns off formatting - - 'file' (literally 'file', not a placeholder) - uses .clang-format file in the closest parent - directory - - '{ }' specifies options inline, e.g. - -format-style='{BasedOnStyle: llvm, IndentWidth: 8}' - - 'llvm', 'google', 'webkit', 'mozilla' -See clang-format documentation for the up-to-date -information about formatting styles and options. -This option overrides the 'FormatStyle` option in -.clang-tidy file, if any. -)"), - cl::init("none"), - cl::cat(ClangTidyCategory)); - -static cl::opt ListChecks("list-checks", cl::desc(R"( -List all enabled checks and exit. Use with --checks=* to list all available checks. -)"), - cl::init(false), cl::cat(ClangTidyCategory)); - -static cl::opt ExplainConfig("explain-config", cl::desc(R"( -For each enabled check explains, where it is -enabled, i.e. in clang-tidy binary, command -line or a specific configuration file. -)"), - cl::init(false), cl::cat(ClangTidyCategory)); - -static cl::opt Config("config", cl::desc(R"( -Specifies a configuration in YAML/JSON format: - -config="{Checks: '*', - CheckOptions: [{key: x, - value: y}]}" -When the value is empty, clang-tidy will -attempt to find a file named .clang-tidy for -each source file in its parent directories. -)"), - cl::init(""), cl::cat(ClangTidyCategory)); - -static cl::opt DumpConfig("dump-config", cl::desc(R"( -Dumps configuration in the YAML format to -stdout. This option can be used along with a -file name (and '--' if the file is outside of a -project with configured compilation database). -The configuration used for this file will be -printed. -Use along with -checks=* to include -configuration of all checks. -)"), - cl::init(false), cl::cat(ClangTidyCategory)); - -static cl::opt EnableCheckProfile("enable-check-profile", cl::desc(R"( -Enable per-check timing profiles, and print a -report to stderr. -)"), - cl::init(false), - cl::cat(ClangTidyCategory)); - -static cl::opt StoreCheckProfile("store-check-profile", - cl::desc(R"( -By default reports are printed in tabulated -format to stderr. When this option is passed, -these per-TU profiles are instead stored as JSON. -)"), - cl::value_desc("prefix"), - cl::cat(ClangTidyCategory)); - -/// This option allows enabling the experimental alpha checkers from the static -/// analyzer. This option is set to false and not visible in help, because it is -/// highly not recommended for users. -static cl::opt - AllowEnablingAnalyzerAlphaCheckers("allow-enabling-analyzer-alpha-checkers", - cl::init(false), cl::Hidden, - cl::cat(ClangTidyCategory)); - -static cl::opt ExportFixes("export-fixes", cl::desc(R"( -YAML file to store suggested fixes in. The -stored fixes can be applied to the input source -code with clang-apply-replacements. -)"), - cl::value_desc("filename"), - cl::cat(ClangTidyCategory)); - -static cl::opt Quiet("quiet", cl::desc(R"( -Run clang-tidy in quiet mode. This suppresses -printing statistics about ignored warnings and -warnings treated as errors if the respective -options are specified. -)"), - cl::init(false), - cl::cat(ClangTidyCategory)); - -static cl::opt VfsOverlay("vfsoverlay", cl::desc(R"( -Overlay the virtual filesystem described by file -over the real file system. -)"), - cl::value_desc("filename"), - cl::cat(ClangTidyCategory)); - -namespace clang { -namespace tidy { - -static void printStats(const ClangTidyStats &Stats) { - if (Stats.errorsIgnored()) { - llvm::errs() << "Suppressed " << Stats.errorsIgnored() << " warnings ("; - StringRef Separator = ""; - if (Stats.ErrorsIgnoredNonUserCode) { - llvm::errs() << Stats.ErrorsIgnoredNonUserCode << " in non-user code"; - Separator = ", "; - } - if (Stats.ErrorsIgnoredLineFilter) { - llvm::errs() << Separator << Stats.ErrorsIgnoredLineFilter - << " due to line filter"; - Separator = ", "; - } - if (Stats.ErrorsIgnoredNOLINT) { - llvm::errs() << Separator << Stats.ErrorsIgnoredNOLINT << " NOLINT"; - Separator = ", "; - } - if (Stats.ErrorsIgnoredCheckFilter) - llvm::errs() << Separator << Stats.ErrorsIgnoredCheckFilter - << " with check filters"; - llvm::errs() << ").\n"; - if (Stats.ErrorsIgnoredNonUserCode) - llvm::errs() << "Use -header-filter=.* to display errors from all " - "non-system headers. Use -system-headers to display " - "errors from system headers as well.\n"; - } -} - -static std::unique_ptr createOptionsProvider( - llvm::IntrusiveRefCntPtr FS) { - ClangTidyGlobalOptions GlobalOptions; - if (std::error_code Err = parseLineFilter(LineFilter, GlobalOptions)) { - llvm::errs() << "Invalid LineFilter: " << Err.message() << "\n\nUsage:\n"; - llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true); - return nullptr; - } - - ClangTidyOptions DefaultOptions; - DefaultOptions.Checks = DefaultChecks; - DefaultOptions.WarningsAsErrors = ""; - DefaultOptions.HeaderFilterRegex = HeaderFilter; - DefaultOptions.SystemHeaders = SystemHeaders; - DefaultOptions.FormatStyle = FormatStyle; - DefaultOptions.User = llvm::sys::Process::GetEnv("USER"); - // USERNAME is used on Windows. - if (!DefaultOptions.User) - DefaultOptions.User = llvm::sys::Process::GetEnv("USERNAME"); - - ClangTidyOptions OverrideOptions; - if (Checks.getNumOccurrences() > 0) - OverrideOptions.Checks = Checks; - if (WarningsAsErrors.getNumOccurrences() > 0) - OverrideOptions.WarningsAsErrors = WarningsAsErrors; - if (HeaderFilter.getNumOccurrences() > 0) - OverrideOptions.HeaderFilterRegex = HeaderFilter; - if (SystemHeaders.getNumOccurrences() > 0) - OverrideOptions.SystemHeaders = SystemHeaders; - if (FormatStyle.getNumOccurrences() > 0) - OverrideOptions.FormatStyle = FormatStyle; - - if (!Config.empty()) { - if (llvm::ErrorOr ParsedConfig = - parseConfiguration(Config)) { - return llvm::make_unique( - GlobalOptions, - ClangTidyOptions::getDefaults().mergeWith(DefaultOptions), - *ParsedConfig, OverrideOptions); - } else { - llvm::errs() << "Error: invalid configuration specified.\n" - << ParsedConfig.getError().message() << "\n"; - return nullptr; - } - } - return llvm::make_unique(GlobalOptions, DefaultOptions, - OverrideOptions, std::move(FS)); -} - -llvm::IntrusiveRefCntPtr -getVfsOverlayFromFile(const std::string &OverlayFile) { - llvm::IntrusiveRefCntPtr OverlayFS( - new vfs::OverlayFileSystem(vfs::getRealFileSystem())); - llvm::ErrorOr> Buffer = - OverlayFS->getBufferForFile(OverlayFile); - if (!Buffer) { - llvm::errs() << "Can't load virtual filesystem overlay file '" - << OverlayFile << "': " << Buffer.getError().message() - << ".\n"; - return nullptr; - } - - IntrusiveRefCntPtr FS = vfs::getVFSFromYAML( - std::move(Buffer.get()), /*DiagHandler*/ nullptr, OverlayFile); - if (!FS) { - llvm::errs() << "Error: invalid virtual filesystem overlay file '" - << OverlayFile << "'.\n"; - return nullptr; - } - OverlayFS->pushOverlay(FS); - return OverlayFS; -} - -static int clangTidyMain(int argc, const char **argv) { - CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory, - cl::ZeroOrMore); - llvm::IntrusiveRefCntPtr BaseFS( - VfsOverlay.empty() ? vfs::getRealFileSystem() - : getVfsOverlayFromFile(VfsOverlay)); - if (!BaseFS) - return 1; - - auto OwningOptionsProvider = createOptionsProvider(BaseFS); - auto *OptionsProvider = OwningOptionsProvider.get(); - if (!OptionsProvider) - return 1; - - auto MakeAbsolute = [](const std::string &Input) -> SmallString<256> { - if (Input.empty()) - return {}; - SmallString<256> AbsolutePath(Input); - if (std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath)) { - llvm::errs() << "Can't make absolute path from " << Input << ": " - << EC.message() << "\n"; - } - return AbsolutePath; - }; - - SmallString<256> ProfilePrefix = MakeAbsolute(StoreCheckProfile); - - StringRef FileName("dummy"); - auto PathList = OptionsParser.getSourcePathList(); - if (!PathList.empty()) { - FileName = PathList.front(); - } - - SmallString<256> FilePath = MakeAbsolute(FileName); - - ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FilePath); - std::vector EnabledChecks = - getCheckNames(EffectiveOptions, AllowEnablingAnalyzerAlphaCheckers); - - if (ExplainConfig) { - // FIXME: Show other ClangTidyOptions' fields, like ExtraArg. - std::vector - RawOptions = OptionsProvider->getRawOptions(FilePath); - for (const std::string &Check : EnabledChecks) { - for (auto It = RawOptions.rbegin(); It != RawOptions.rend(); ++It) { - if (It->first.Checks && GlobList(*It->first.Checks).contains(Check)) { - llvm::outs() << "'" << Check << "' is enabled in the " << It->second - << ".\n"; - break; - } - } - } - return 0; - } - - if (ListChecks) { - if (EnabledChecks.empty()) { - llvm::errs() << "No checks enabled.\n"; - return 1; - } - llvm::outs() << "Enabled checks:"; - for (const auto &CheckName : EnabledChecks) - llvm::outs() << "\n " << CheckName; - llvm::outs() << "\n\n"; - return 0; - } - - if (DumpConfig) { - EffectiveOptions.CheckOptions = - getCheckOptions(EffectiveOptions, AllowEnablingAnalyzerAlphaCheckers); - llvm::outs() << configurationAsText( - ClangTidyOptions::getDefaults().mergeWith( - EffectiveOptions)) - << "\n"; - return 0; - } - - if (EnabledChecks.empty()) { - llvm::errs() << "Error: no checks enabled.\n"; - llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true); - return 1; - } - - if (PathList.empty()) { - llvm::errs() << "Error: no input files specified.\n"; - llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true); - return 1; - } - - llvm::InitializeAllTargetInfos(); - llvm::InitializeAllTargetMCs(); - llvm::InitializeAllAsmParsers(); - - ClangTidyContext Context(std::move(OwningOptionsProvider), - AllowEnablingAnalyzerAlphaCheckers); - runClangTidy(Context, OptionsParser.getCompilations(), PathList, BaseFS, - EnableCheckProfile, ProfilePrefix); - ArrayRef Errors = Context.getErrors(); - bool FoundErrors = llvm::find_if(Errors, [](const ClangTidyError &E) { - return E.DiagLevel == ClangTidyError::Error; - }) != Errors.end(); - - const bool DisableFixes = Fix && FoundErrors && !FixErrors; - - unsigned WErrorCount = 0; - - // -fix-errors implies -fix. - handleErrors(Context, (FixErrors || Fix) && !DisableFixes, WErrorCount, - BaseFS); - - if (!ExportFixes.empty() && !Errors.empty()) { - std::error_code EC; - llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None); - if (EC) { - llvm::errs() << "Error opening output file: " << EC.message() << '\n'; - return 1; - } - exportReplacements(FilePath.str(), Errors, OS); - } - - if (!Quiet) { - printStats(Context.getStats()); - if (DisableFixes) - llvm::errs() - << "Found compiler errors, but -fix-errors was not specified.\n" - "Fixes have NOT been applied.\n\n"; - } - - if (WErrorCount) { - if (!Quiet) { - StringRef Plural = WErrorCount == 1 ? "" : "s"; - llvm::errs() << WErrorCount << " warning" << Plural << " treated as error" - << Plural << "\n"; - } - return WErrorCount; - } - - if (FoundErrors) { - // TODO: Figure out when zero exit code should be used with -fix-errors: - // a. when a fix has been applied for an error - // b. when a fix has been applied for all errors - // c. some other condition. - // For now always returning zero when -fix-errors is used. - if (FixErrors) - return 0; - if (!Quiet) - llvm::errs() << "Found compiler error(s).\n"; - return 1; - } - - return 0; -} - -// This anchor is used to force the linker to link the CERTModule. -extern volatile int CERTModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED CERTModuleAnchorDestination = - CERTModuleAnchorSource; - -// This anchor is used to force the linker to link the AbseilModule. -extern volatile int AbseilModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED AbseilModuleAnchorDestination = - AbseilModuleAnchorSource; - -// This anchor is used to force the linker to link the BoostModule. -extern volatile int BoostModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED BoostModuleAnchorDestination = - BoostModuleAnchorSource; - -// This anchor is used to force the linker to link the BugproneModule. -extern volatile int BugproneModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED BugproneModuleAnchorDestination = - BugproneModuleAnchorSource; - -// This anchor is used to force the linker to link the LLVMModule. -extern volatile int LLVMModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED LLVMModuleAnchorDestination = - LLVMModuleAnchorSource; - -// This anchor is used to force the linker to link the CppCoreGuidelinesModule. -extern volatile int CppCoreGuidelinesModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED CppCoreGuidelinesModuleAnchorDestination = - CppCoreGuidelinesModuleAnchorSource; - -// This anchor is used to force the linker to link the FuchsiaModule. -extern volatile int FuchsiaModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED FuchsiaModuleAnchorDestination = - FuchsiaModuleAnchorSource; - -// This anchor is used to force the linker to link the GoogleModule. -extern volatile int GoogleModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED GoogleModuleAnchorDestination = - GoogleModuleAnchorSource; - -// This anchor is used to force the linker to link the AndroidModule. -extern volatile int AndroidModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED AndroidModuleAnchorDestination = - AndroidModuleAnchorSource; - -// This anchor is used to force the linker to link the MiscModule. -extern volatile int MiscModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED MiscModuleAnchorDestination = - MiscModuleAnchorSource; - -// This anchor is used to force the linker to link the ModernizeModule. -extern volatile int ModernizeModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED ModernizeModuleAnchorDestination = - ModernizeModuleAnchorSource; - -// This anchor is used to force the linker to link the MPIModule. -extern volatile int MPIModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED MPIModuleAnchorDestination = - MPIModuleAnchorSource; - -// This anchor is used to force the linker to link the PerformanceModule. -extern volatile int PerformanceModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED PerformanceModuleAnchorDestination = - PerformanceModuleAnchorSource; - -// This anchor is used to force the linker to link the PortabilityModule. -extern volatile int PortabilityModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED PortabilityModuleAnchorDestination = - PortabilityModuleAnchorSource; - -// This anchor is used to force the linker to link the ReadabilityModule. -extern volatile int ReadabilityModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED ReadabilityModuleAnchorDestination = - ReadabilityModuleAnchorSource; - -// This anchor is used to force the linker to link the ObjCModule. -extern volatile int ObjCModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED ObjCModuleAnchorDestination = - ObjCModuleAnchorSource; - -// This anchor is used to force the linker to link the HICPPModule. -extern volatile int HICPPModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED HICPPModuleAnchorDestination = - HICPPModuleAnchorSource; - -// This anchor is used to force the linker to link the ZirconModule. -extern volatile int ZirconModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED ZirconModuleAnchorDestination = - ZirconModuleAnchorSource; - -// This anchor is used to force the linker to link the AliceO2Module. -extern volatile int AliceO2ModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED AliceO2ModuleAnchorDestination = - AliceO2ModuleAnchorSource; - -// This anchor is used to force the linker to link the ReportingModule. -extern volatile int ReportingModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED ReportingModuleAnchorDestination = - ReportingModuleAnchorSource; - -} // namespace tidy -} // namespace clang - -int main(int argc, const char **argv) { - return clang::tidy::clangTidyMain(argc, argv); -} diff --git a/tool/clang-tidy-diff.py b/tool/clang-tidy-diff.py deleted file mode 100755 index e3dcbe7..0000000 --- a/tool/clang-tidy-diff.py +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/env python -# -#===- clang-tidy-diff.py - ClangTidy Diff Checker ------------*- python -*--===# -# -# The LLVM Compiler Infrastructure -# -# This file is distributed under the University of Illinois Open Source -# License. See LICENSE.TXT for details. -# -#===------------------------------------------------------------------------===# - -r""" -ClangTidy Diff Checker -====================== - -This script reads input from a unified diff, runs clang-tidy on all changed -files and outputs clang-tidy warnings in changed lines only. This is useful to -detect clang-tidy regressions in the lines touched by a specific patch. -Example usage for git/svn users: - - git diff -U0 HEAD^ | clang-tidy-diff.py -p1 - svn diff --diff-cmd=diff -x-U0 | \ - clang-tidy-diff.py -fix -checks=-*,modernize-use-override - -""" - -import argparse -import json -import re -import subprocess -import sys - - -def main(): - parser = argparse.ArgumentParser(description= - 'Run clang-tidy against changed files, and ' - 'output diagnostics only for modified ' - 'lines.') - parser.add_argument('-clang-tidy-binary', metavar='PATH', - default='clang-tidy', - help='path to clang-tidy binary') - parser.add_argument('-p', metavar='NUM', default=0, - help='strip the smallest prefix containing P slashes') - parser.add_argument('-regex', metavar='PATTERN', default=None, - help='custom pattern selecting file paths to check ' - '(case sensitive, overrides -iregex)') - parser.add_argument('-iregex', metavar='PATTERN', default= - r'.*\.(cpp|cc|c\+\+|cxx|c|cl|h|hpp|m|mm|inc)', - help='custom pattern selecting file paths to check ' - '(case insensitive, overridden by -regex)') - - parser.add_argument('-fix', action='store_true', default=False, - help='apply suggested fixes') - parser.add_argument('-checks', - help='checks filter, when not specified, use clang-tidy ' - 'default', - default='') - clang_tidy_args = [] - argv = sys.argv[1:] - if '--' in argv: - clang_tidy_args.extend(argv[argv.index('--'):]) - argv = argv[:argv.index('--')] - - args = parser.parse_args(argv) - - # Extract changed lines for each file. - filename = None - lines_by_file = {} - for line in sys.stdin: - match = re.search('^\+\+\+\ \"?(.*?/){%s}([^ \t\n\"]*)' % args.p, line) - if match: - filename = match.group(2) - if filename == None: - continue - - if args.regex is not None: - if not re.match('^%s$' % args.regex, filename): - continue - else: - if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE): - continue - - match = re.search('^@@.*\+(\d+)(,(\d+))?', line) - if match: - start_line = int(match.group(1)) - line_count = 1 - if match.group(3): - line_count = int(match.group(3)) - if line_count == 0: - continue - end_line = start_line + line_count - 1; - lines_by_file.setdefault(filename, []).append([start_line, end_line]) - - if len(lines_by_file) == 0: - print("No relevant changes found.") - sys.exit(0) - - line_filter_json = json.dumps( - [{"name" : name, "lines" : lines_by_file[name]} for name in lines_by_file], - separators = (',', ':')) - - quote = ""; - if sys.platform == 'win32': - line_filter_json=re.sub(r'"', r'"""', line_filter_json) - else: - quote = "'"; - - # Run clang-tidy on files containing changes. - command = [args.clang_tidy_binary] - command.append('-line-filter=' + quote + line_filter_json + quote) - if args.fix: - command.append('-fix') - if args.checks != '': - command.append('-checks=' + quote + args.checks + quote) - command.extend(lines_by_file.keys()) - command.extend(clang_tidy_args) - - sys.exit(subprocess.call(' '.join(command), shell=True)) - -if __name__ == '__main__': - main() diff --git a/tool/run_O2CodeChecker.py b/tool/run_O2CodeChecker.py index 3ca2a42..8952871 100755 --- a/tool/run_O2CodeChecker.py +++ b/tool/run_O2CodeChecker.py @@ -34,11 +34,15 @@ http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html """ +from __future__ import print_function import argparse import json import multiprocessing import os -import Queue +try: + import Queue +except ImportError: + import queue as Queue import re import shutil import subprocess @@ -52,14 +56,14 @@ def find_compilation_database(path): result = './' while not os.path.isfile(os.path.join(result, path)): if os.path.realpath(result) == '/': - print 'Error: could not find compilation database.' + print('Error: could not find compilation database.') sys.exit(1) result += '../' return os.path.realpath(result) def get_tidy_invocation(f, clang_tidy_binary, checks, warningsAsErrors, tmpdir, build_path, - header_filter, config): + header_filter, config, extra_args): """Gets a command line for clang-tidy.""" start = [clang_tidy_binary] if header_filter is not None: @@ -73,6 +77,8 @@ def get_tidy_invocation(f, clang_tidy_binary, checks, warningsAsErrors, tmpdir, start.append('-warnings-as-errors=' + warningsAsErrors) if config: start.append('-config=' + config) + for extra in extra_args: + start.append(extra) if tmpdir is not None: start.append('-export-fixes') # Get a temporary file. We immediately close the handle so clang-tidy can @@ -82,6 +88,7 @@ def get_tidy_invocation(f, clang_tidy_binary, checks, warningsAsErrors, tmpdir, start.append(name) start.append('-p=' + build_path) start.append(f) + start.append('--extra-arg=-fopenmp') return start @@ -100,7 +107,7 @@ def run_tidy(args, tmpdir, build_path, queue): while True: name = queue.get() invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks, args.warningsAsErrors, - tmpdir, build_path, args.header_filter, args.config) + tmpdir, build_path, args.header_filter, args.config, args.extra_args) sys.stdout.write(' '.join(invocation) + '\n') subprocess.call(invocation) queue.task_done() @@ -126,6 +133,8 @@ def main(): parser.add_argument('-config', default=None, help='config option for check , when not specified, use clang-tidy ' 'default') + parser.add_argument('-extra-args', default=None, + help='Extra arguments to pass to o2codechecker') parser.add_argument('-header-filter', default=None, help='regular expression matching the names of the ' 'headers to output diagnostics from. Diagnostics from ' @@ -143,6 +152,8 @@ def main(): args = parser.parse_args() db_path = 'compile_commands.json' + if args.extra_args: + args.extra_args = args.extra_args.split(" ") if args.build_path is not None: build_path = args.build_path @@ -158,9 +169,9 @@ def main(): if args.checks: invocation.append('-checks=' + args.checks) invocation.append('-') - print subprocess.check_output(invocation) + print(subprocess.check_output(invocation)) except: - print >>sys.stderr, "Unable to run clang-tidy." + print("Unable to run clang-tidy.") sys.exit(1) # Load the database and extract all files. @@ -198,13 +209,13 @@ def main(): except KeyboardInterrupt: # This is a sad hack. Unfortunately subprocess goes # bonkers with ctrl-c and we start forking merrily. - print '\nCtrl-C detected, goodbye.' + print('\nCtrl-C detected, goodbye.') if args.fix: shutil.rmtree(tmpdir) os.kill(0, 9) if args.fix: - print 'Applying fixes ...' + print('Applying fixes ...') apply_fixes(args, tmpdir) if __name__ == '__main__': diff --git a/utility/ThinCompilationsDatabase.py b/utility/ThinCompilationsDatabase.py index 8fccb52..e83b21a 100755 --- a/utility/ThinCompilationsDatabase.py +++ b/utility/ThinCompilationsDatabase.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # A python script with the goal # to transform a (large) compilations database @@ -9,13 +9,17 @@ # # First version: Sandro Wenzel (June 2017) +from __future__ import print_function import argparse import json import os import subprocess import re # these are for queue syncronized multi-threading -import Queue +try: + import Queue +except ImportError: + import queue as Queue import threading import multiprocessing import time @@ -45,7 +49,7 @@ def parseArgs(): def verboseLog(string, level=0): global verbosity if verbosity > 0: - print string + print(string) def getListOfChangedFiles(colonseparatedfilepaths): """ processes the argument '-use-files' and returns a python list of filenames """ @@ -94,14 +98,21 @@ def modifyCompileCommand(command): def matchesHeader(line, header): expression=".*\.h" # make this more efficient by compiling the expression - return re.match(expression, line) is not None + try: + return re.match(expression, line.decode("utf-8")) is not None + except: + return re.match(expression, line) is not None + def queryListOfHeaders(command): proc=subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) headerlist=[] for line in proc.stdout: - if matchesHeader(line.strip(), headerlist): - headerlist.append(line.strip()) + line = line.strip() + if matchesHeader(line, headerlist): + if isinstance(line, bytes): + line = line.decode('utf-8') + headerlist.append(line) return headerlist # service that processes one item in the queue @@ -128,8 +139,8 @@ def processItem(keepalive, changedheaderlist, queue, outqueue): def reportProgress(keepalive, queue, q2): while len(keepalive)>0: - print "input queue has size " + str(queue.qsize()) - print "output queue has size " + str(q2.qsize()) + print("input queue has size " + str(queue.qsize())) + print("output queue has size " + str(q2.qsize())) time.sleep(1) #custom function to remove duplicates and return a new list @@ -173,11 +184,11 @@ def main(): #setup the isInvalid (closure) function isInvalid=makeInvalidClosure(args) - #open the compilations database + #open the compilations database try: file=open('compile_commands.json').read() except IOError: - print "Problem opening the compilation database (file not found)" + print("Problem opening the compilation database (file not found)") sys.exit(1) #convert json to dict