diff --git a/CMakeLists.txt b/CMakeLists.txt index 8d03157..6ae97bd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,55 +1,40 @@ -cmake_minimum_required(VERSION 3.4.3) +cmake_minimum_required(VERSION 4.0) 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) - +project(O2CodeChecker) - # find clang + llvm - find_package(Clang REQUIRED) +# LLVM's installed HandleLLVMOptions.cmake sets no C++ standard, so without this +# we inherit whatever the compiler defaults to -- C++14 on Apple clang, which is +# not enough for the clang-tidy headers. +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) - if( LLVM_FOUND ) - list(APPEND CMAKE_MODULE_PATH "${LLVM_CMAKE_DIR}") - include(AddLLVM) +# find clang + llvm +find_package(Clang REQUIRED CONFIG) - # set the compiler flags to match llvm - include(HandleLLVMOptions) - endif() +if( LLVM_FOUND ) + list(APPEND CMAKE_MODULE_PATH "${LLVM_CMAKE_DIR}") + include(AddLLVM) - # 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") - - # 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) -endif() +# some extra utilities +add_subdirectory(utility) diff --git a/ClangTidy.h b/ClangTidy.h deleted file mode 100644 index 5c2721c..0000000 --- a/ClangTidy.h +++ /dev/null @@ -1,236 +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 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: - typedef std::vector> CheckersList; - CheckersList getCheckersControlList(GlobList &Filter); - - 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); - -/// \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); - -/// \brief Run a set of clang-tidy checks on a set of files. -/// -/// \param Profile if provided, it enables check profile collection in -/// MatchFinder, and will contain the result of the profile. -ClangTidyStats -runClangTidy(std::unique_ptr OptionsProvider, - const tooling::CompilationDatabase &Compilations, - ArrayRef InputFiles, - std::vector *Errors, - ProfileData *Profile = nullptr); - -// 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. -void handleErrors(const std::vector &Errors, bool Fix, - unsigned &WarningsAsErrorsCount); - -/// \brief Serializes replacements into YAML and writes them to the specified -/// output stream. -void exportReplacements(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 d7e4d2b..0000000 --- a/ClangTidyDiagnosticConsumer.h +++ /dev/null @@ -1,293 +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 "clang/Basic/Diagnostic.h" -#include "clang/Basic/SourceManager.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 message from a clang-tidy check. -/// -/// Note that this is independent of a \c SourceManager. -struct ClangTidyMessage { - ClangTidyMessage(StringRef Message = ""); - ClangTidyMessage(StringRef Message, const SourceManager &Sources, - SourceLocation Loc); - std::string Message; - std::string FilePath; - unsigned FileOffset; -}; - -/// \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 { - enum Level { - Warning = DiagnosticsEngine::Warning, - Error = DiagnosticsEngine::Error - }; - - ClangTidyError(StringRef CheckName, Level DiagLevel, bool IsWarningAsError, - StringRef BuildDirectory); - - std::string CheckName; - ClangTidyMessage Message; - tooling::Replacements Fix; - SmallVector Notes; - - // A build directory of the diagnostic source file. - // - // It's an absolute path which is `directory` field of the source file in - // compilation database. If users don't specify the compilation database - // directory, it is the current directory where clang-tidy runs. - // - // Note: it is empty in unittest. - std::string BuildDirectory; - - Level DiagLevel; - 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 Container for clang-tidy profiling data. -struct ProfileData { - llvm::StringMap Records; -}; - -/// \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); - - /// \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 check filter for the \c CurrentFile. - /// - /// The \c CurrentFile can be changed using \c setCurrentFile. - GlobList &getChecksFilter(); - - /// \brief Returns check filter for the \c CurrentFile which - /// selects checks for upgrade to error. - GlobList &getWarningAsErrorFilter(); - - /// \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. - const std::vector &getErrors() const { return Errors; } - - /// \brief Clears collected errors. - void clearErrors() { Errors.clear(); } - - /// \brief Set the output struct for profile data. - /// - /// Setting a non-null pointer here will enable profile collection in - /// clang-tidy. - void setCheckProfileData(ProfileData *Profile); - ProfileData *getCheckProfileData() const { return Profile; } - - /// \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; - } - -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; - std::unique_ptr CheckFilter; - std::unique_ptr WarningAsErrorFilter; - - LangOptions LangOpts; - - ClangTidyStats Stats; - - std::string CurrentBuildDirectory; - - llvm::DenseMap CheckNamesByDiagnosticID; - - ProfileData *Profile; -}; - -/// \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); - - // 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; - std::unique_ptr Diags; - SmallVector Errors; - std::unique_ptr HeaderFilter; - bool LastErrorRelatesToUserCode; - bool LastErrorPassesLineFilter; -}; - -} // 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 58e833c..0000000 --- a/ClangTidyModule.h +++ /dev/null @@ -1,98 +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 de2a3d7..0000000 --- a/ClangTidyModuleRegistry.h +++ /dev/null @@ -1,26 +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" - -extern template class llvm::Registry; - -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 74a483f..0000000 --- a/ClangTidyOptions.h +++ /dev/null @@ -1,259 +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/Support/ErrorOr.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 Turns on temporary destructor-based analysis. - llvm::Optional AnalyzeTemporaryDtors; - - /// \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); - - /// \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; -}; - -/// \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/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/add_new_check.py b/add_new_check.py index 868ccd1..d414a2b 100755 --- a/add_new_check.py +++ b/add_new_check.py @@ -26,6 +26,7 @@ def adapt_cmake(module_path, check_name_camel): # Figure out whether this check already exists. for line in lines: if line.strip() == cpp_file: + print "cpp file already exists!", cpp_file return False print('Updating %s...' % filename) @@ -191,9 +192,14 @@ def adapt_module(module_path, module, check_name, check_name_camel): # Adds a test for the check. def write_test(module_path, module, check_name): + check_name_dashes = module + '-' + check_name - filename = os.path.normpath(os.path.join(module_path, '../../test/clang-tidy', - check_name_dashes + '.cpp')) + filepath = os.path.join(module_path, '../test/') + if not os.path.exists(filepath): + os.makedirs(filepath) + + filename = os.path.normpath(os.path.join(filepath, check_name_dashes + '.cpp')) + print('Creating %s...' % filename) with open(filename, 'wb') as f: f.write("""// RUN: %%check_clang_tidy %%s %(check_name_dashes)s %%t @@ -215,8 +221,21 @@ def write_test(module_path, module, check_name): # Recreates the list of checks in the docs/clang-tidy/checks directory. def update_checks_list(clang_tidy_path): - docs_dir = os.path.join(clang_tidy_path, '../docs/clang-tidy/checks') + docs_dir = os.path.join(clang_tidy_path, './docs/clang-tidy/checks') filename = os.path.normpath(os.path.join(docs_dir, 'list.rst')) + + if not os.path.exists(filename): + os.mknod(filename) + print 'Creating file ', filename + with open(filename, 'w') as f: + f.write('.. title:: clang-tidy - Clang-Tidy Checks\n') + f.write('\n') + f.write('Clang-Tidy Checks\n') + f.write('=========================\n') + f.write('\n') + f.write('.. toctree::\n') + f.write('\n') + with open(filename, 'r') as f: lines = f.readlines() doc_files = filter(lambda s: s.endswith('.rst') and s != 'list.rst', @@ -249,8 +268,12 @@ def format_link(doc_file): # Adds a documentation for the check. def write_docs(module_path, module, check_name): check_name_dashes = module + '-' + check_name - filename = os.path.normpath(os.path.join( - module_path, '../../docs/clang-tidy/checks/', check_name_dashes + '.rst')) + filepath = os.path.join(module_path, '../docs/clang-tidy/checks/') + filename = os.path.normpath(os.path.join(filepath, check_name_dashes + '.rst')) + + if not os.path.exists(filepath): + os.makedirs(filepath) + print('Creating %s...' % filename) with open(filename, 'wb') as f: f.write(""".. title:: clang-tidy - %(check_name_dashes)s @@ -290,8 +313,12 @@ def main(): clang_tidy_path = os.path.dirname(sys.argv[0]) module_path = os.path.join(clang_tidy_path, module) + if not os.path.exists(module_path): + os.makedirs(module_path) + if not adapt_cmake(module_path, check_name_camel): return + write_header(module_path, module, check_name, check_name_camel) write_implementation(module_path, module, check_name_camel) adapt_module(module_path, module, check_name, check_name_camel) diff --git a/aliceO2/AliceO2TidyModule.cpp b/aliceO2/AliceO2TidyModule.cpp index 1df9b00..4c6f73d 100644 --- a/aliceO2/AliceO2TidyModule.cpp +++ b/aliceO2/AliceO2TidyModule.cpp @@ -7,10 +7,18 @@ // //===----------------------------------------------------------------------===// -#include "../ClangTidy.h" -#include "../ClangTidyModule.h" -#include "../ClangTidyModuleRegistry.h" +#include "clang-tidy/ClangTidy.h" +#include "clang-tidy/ClangTidyModule.h" +// Up to Clang 21 ClangTidyModuleRegistry was declared only in +// ClangTidyModuleRegistry.h. Clang 22 moved it into ClangTidyModule.h above and +// left the old header behind as a bare #warning, to be deleted in Clang 24 -- +// so __has_include() would keep including it, and keep warning, on 22 and 23. +#include "llvm/Config/llvm-config.h" +#if LLVM_VERSION_MAJOR < 22 +#include "clang-tidy/ClangTidyModuleRegistry.h" +#endif #include "MemberNamesCheck.h" +#include "NamespaceNamingCheck.h" #include "SizeofCheck.h" namespace clang { @@ -20,17 +28,22 @@ namespace aliceO2 { class AliceO2Module : public ClangTidyModule { public: void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override { - CheckFactories.registerCheck("aliceO2-member-name"); + CheckFactories.registerCheck( + "aliceO2-member-name"); + CheckFactories.registerCheck( + "aliceO2-namespace-naming"); CheckFactories.registerCheck( "aliceO2-SizeOf"); } }; + } // namespace aliceO2 // Register the AliceO2TidyModule using this statically initialized variable. -static ClangTidyModuleRegistry::Add -X("aliceO2-module", "Adds AliceO2 specific checks"); +static ClangTidyModuleRegistry::Add X("aliceO2-module", + "Adds AliceO2 specific checks"); + // This anchor is used to force the linker to link in the generated object file // and thus register the AliceO2Module. diff --git a/aliceO2/CMakeLists.txt b/aliceO2/CMakeLists.txt index 145a03a..e00c918 100644 --- a/aliceO2/CMakeLists.txt +++ b/aliceO2/CMakeLists.txt @@ -1,16 +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 - 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 new file mode 100644 index 0000000..000399b --- /dev/null +++ b/aliceO2/NamespaceNamingCheck.cpp @@ -0,0 +1,191 @@ +//===--- NamespaceNamingCheck.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 "NamespaceNamingCheck.h" +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchersMacros.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "llvm/Config/llvm-config.h" // LLVM_VERSION_MAJOR +#include +#include +#include + +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 { + +const std::string VALID_NAME_REGEX = "[a-z][a-z_0-9]+"; +std::string VALID_PATH_REGEX = ""; + +NamespaceNamingCheck::NamespaceNamingCheck(StringRef Name, ClangTidyContext *Context) + : ClangTidyCheck(Name, Context) +{ + VALID_PATH_REGEX = Options.getLocalOrGlobal("CheckPathRegex",""); + if( VALID_PATH_REGEX == "" ) + { + fprintf(stderr,"Error: User must provide a .clang-tidy file in any of the parent directories of the source files containing a key-value pair for key \'CheckPathRegex\' " + "or pass the key-value pair with the command line argument --config"); + exit(1); + } +} + +bool isOutsideOfTargetScope(std::string filename) +{ + return !std::regex_match(filename, std::regex(VALID_PATH_REGEX)); +} + +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(allOf( + inO2NSMatch, + unless(validNameMatch) + ))))).bind("namespace-usage"), this); + // matches "using namespace" declarations + Finder->addMatcher(usingDirectiveDecl(allOf( + unless(isImplicit()), + nominatedNamespace(allOf( + inO2NSMatch, + unless(validNameMatch) + )))).bind("using-namespace"), this); +} + +void NamespaceNamingCheck::check(const MatchFinder::MatchResult &Result) { + const auto *MatchedNamespaceDecl = Result.Nodes.getNodeAs("namespace-decl"); + if( MatchedNamespaceDecl ) + { + if( isOutsideOfTargetScope( Result.SourceManager->getFilename(MatchedNamespaceDecl->getLocation()).str() ) ) + { + return; + } + std::string newName(MatchedNamespaceDecl->getDeclName().getAsString()); + std::string oldName=newName; + + if(fixNamespaceName(newName)) + { + diag(MatchedNamespaceDecl->getLocation(), "namespace %q0 does not follow the underscore convention") + << MatchedNamespaceDecl + << FixItHint::CreateReplacement(MatchedNamespaceDecl->getLocation(), newName); + } + else + { + logNameError(MatchedNamespaceDecl->getLocation(), oldName); + } + } + + const auto *MatchedNamespaceLoc = Result.Nodes.getNodeAs("namespace-usage"); + if( MatchedNamespaceLoc ) + { +#if LLVM_VERSION_MAJOR >= 22 + // Clang 22 turned NestedNameSpecifier into a value type and removed + // getAsNamespace(); the namespace is now reached through + // getAsNamespaceAndPrefix(), which is llvm_unreachable() unless the + // specifier really designates one. The matcher below only binds + // specifiesNamespace(), but check the kind rather than trust that. It also + // yields a NamespaceBaseDecl, the new common base of NamespaceDecl and + // NamespaceAliasDecl; both are NamedDecl, which is all we use below. + const NestedNameSpecifier Qualifier = MatchedNamespaceLoc->getNestedNameSpecifier(); + if( Qualifier.getKind() != NestedNameSpecifier::Kind::Namespace ) + { + return; + } + const NamespaceBaseDecl *AsNamespace = Qualifier.getAsNamespaceAndPrefix().Namespace; +#else + const NamespaceDecl *AsNamespace = MatchedNamespaceLoc->getNestedNameSpecifier()->getAsNamespace(); +#endif + if( isOutsideOfTargetScope( Result.SourceManager->getFilename(AsNamespace->getLocation()).str() ) ) + { + return; + } + std::string newName(AsNamespace->getDeclName().getAsString()); + std::string oldName=newName; + + if(fixNamespaceName(newName)) + { + diag(MatchedNamespaceLoc->getLocalBeginLoc(), "namespace %q0 does not follow the underscore convention") + << AsNamespace + << FixItHint::CreateReplacement(MatchedNamespaceLoc->getLocalBeginLoc(), newName); + } + else + { + logNameError(MatchedNamespaceLoc->getLocalBeginLoc(), oldName); + } + } + + const auto *MatchedUsingNamespace = Result.Nodes.getNodeAs("using-namespace"); + if( MatchedUsingNamespace ) + { + if( isOutsideOfTargetScope( Result.SourceManager->getFilename(MatchedUsingNamespace->getNominatedNamespace()->getLocation()).str() ) ) + { + return; + } + std::string newName(MatchedUsingNamespace->getNominatedNamespace()->getDeclName().getAsString()); + std::string oldName=newName; + + if(fixNamespaceName(newName)) + { + diag(MatchedUsingNamespace->getLocation(), "namespace %q0 does not follow the underscore convention") + << MatchedUsingNamespace->getNominatedNamespace() + << FixItHint::CreateReplacement(MatchedUsingNamespace->getLocation(), newName); + } + else + { + logNameError(MatchedNamespaceDecl->getLocation(), oldName); + } + } +} + +bool NamespaceNamingCheck::fixNamespaceName(std::string &name) +{ + std::string replace_option = Options.get(name, "").str(); + if( replace_option != "" ) + { + name = replace_option; + return true; + } + + for(int i=name.size()-1; i>=0; i--) { + if(isupper(name[i])) { + if(i != 0 && islower(name[i-1])) { + name.insert(i, "_"); + i++; + } + name[i] = tolower(name[i]); + } + } + + return std::regex_match( name, std::regex(VALID_NAME_REGEX) ); +} + +void NamespaceNamingCheck::logNameError(SourceLocation Loc, std::string errorName) +{ + diag(Loc, "Could not fix \'%0\'", DiagnosticIDs::Level::Error) + << errorName; +} + +} // namespace aliceO2 +} // namespace tidy +} // namespace clang diff --git a/aliceO2/NamespaceNamingCheck.h b/aliceO2/NamespaceNamingCheck.h new file mode 100644 index 0000000..b5c08fc --- /dev/null +++ b/aliceO2/NamespaceNamingCheck.h @@ -0,0 +1,38 @@ +//===--- NamespaceNamingCheck.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_ALICEO2_NAMESPACE_NAMING_H +#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ALICEO2_NAMESPACE_NAMING_H + +#include "clang-tidy/ClangTidy.h" +#include "clang-tidy/ClangTidyCheck.h" + +namespace clang { +namespace tidy { +namespace aliceO2 { + +/// FIXME: Write a short description. +/// +/// For the user-facing documentation see: +/// http://clang.llvm.org/extra/clang-tidy/checks/aliceO2-namespace-naming.html +class NamespaceNamingCheck : public ClangTidyCheck { +public: + NamespaceNamingCheck(StringRef Name, ClangTidyContext *Context); + void registerMatchers(ast_matchers::MatchFinder *Finder) override; + void check(const ast_matchers::MatchFinder::MatchResult &Result) override; + + bool fixNamespaceName(std::string &name); + void logNameError(SourceLocation Loc, std::string errorName); +}; + +} // namespace aliceO2 +} // namespace tidy +} // namespace clang + +#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ALICEO2_NAMESPACE_NAMING_H 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/check_clang_tidy.py b/check_clang_tidy.py new file mode 100755 index 0000000..00da391 --- /dev/null +++ b/check_clang_tidy.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python +# +#===- check_clang_tidy.py - ClangTidy Test Helper ------------*- python -*--===# +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +#===------------------------------------------------------------------------===# +# +# This script is used for unit tests. +# Usage: +# ./check_clang_tidy.py .cpp '' +# Examples: +# ./check_clang_tidy.py test/aliceO2-aliceO2-namespace-naming.cpp 'aliceO2*' +# or +# ./check_clang_tidy.py test/aliceO2-aliceO2-namespace-naming.cpp 'aliceO2-namespace-naming' +# + + +r""" +ClangTidy Test Helper +===================== + +This script runs clang-tidy in fix mode and verify fixes, messages or both. + +Usage: + check_clang_tidy.py [-resource-dir ] \ + \ + -- [optional clang-tidy arguments] + +Example: + // RUN: %check_clang_tidy %s llvm-include-order %t -- -- -isystem %S/Inputs +""" + +import argparse +import re +import subprocess +import sys + + +def write_file(file_name, text): + with open(file_name, 'w') as f: + f.write(text) + f.truncate() + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('-resource-dir') + parser.add_argument('input_file_name') + parser.add_argument('check_name') + parser.add_argument('checktool', nargs='?', default="O2codecheck") + + args, extra_args = parser.parse_known_args() + + resource_dir = args.resource_dir + input_file_name = args.input_file_name + check_name = args.check_name + tool = args.checktool + + extension = '.cpp' + if (input_file_name.endswith('.c')): + extension = '.c' + if (input_file_name.endswith('.hpp')): + extension = '.hpp' + + temp_file_name = input_file_name.replace(extension, '_result'+extension) + + clang_tidy_extra_args = extra_args + if len(clang_tidy_extra_args) == 0: + clang_tidy_extra_args = ['--', '--std=c++11'] if extension == '.cpp' \ + else ['--'] + if resource_dir is not None: + clang_tidy_extra_args.append('-resource-dir=%s' % resource_dir) + + with open(input_file_name, 'r') as input_file: + input_text = input_file.read() + + has_check_fixes = input_text.find('CHECK-FIXES') >= 0 + has_check_messages = input_text.find('CHECK-MESSAGES') >= 0 + + if not has_check_fixes and not has_check_messages: + sys.exit('Neither CHECK-FIXES nor CHECK-MESSAGES found in the input') + + # Remove the contents of the CHECK lines to avoid CHECKs matching on + # themselves. We need to keep the comments to preserve line numbers while + # avoiding empty lines which could potentially trigger formatting-related + # checks. + cleaned_test = re.sub('// *CHECK-[A-Z-]*:[^\r\n]*', '//', input_text) + + write_file(temp_file_name, cleaned_test) + + original_file_name = temp_file_name + ".orig" + write_file(original_file_name, cleaned_test) + + args = [tool, temp_file_name, '-fix', '--checks=-*,' + check_name] + \ + clang_tidy_extra_args + print('Running ' + repr(args) + '...') + + try: + clang_tidy_output = \ + subprocess.check_output(args, stderr=subprocess.STDOUT).decode() + except subprocess.CalledProcessError as e: + clang_tidy_output = e.output.decode() + + try: + diff_output = subprocess.check_output( + ['diff', '-u', original_file_name, temp_file_name], + stderr=subprocess.STDOUT) + except subprocess.CalledProcessError as e: + diff_output = e.output + + if has_check_messages: + messages_file = temp_file_name + '.msg' + write_file(messages_file, clang_tidy_output) + + print('------------------------------ Fixes -----------------------------\n' + + diff_output.decode() + + '\n------------------------------------------------------------------') + + if has_check_fixes: + try: + subprocess.check_output( + ['FileCheck', '-input-file=' + temp_file_name, input_file_name, + '-check-prefix=CHECK-FIXES', '-strict-whitespace'], + stderr=subprocess.STDOUT) + except subprocess.CalledProcessError as e: + print('FileCheck failed:\n' + e.output.decode()) + raise + + if has_check_messages: + try: + subprocess.check_output( + ['FileCheck', '-input-file=' + messages_file, input_file_name, + '-check-prefix=CHECK-MESSAGES', + '-implicit-check-not={{warning|error}}:'], + stderr=subprocess.STDOUT) + except subprocess.CalledProcessError as e: + print('FileCheck failed:\n' + e.output.decode()) + raise + +if __name__ == '__main__': + main() diff --git a/docs/clang-tidy/checks/aliceO2-MemberNamesCheck.rst b/docs/clang-tidy/checks/aliceO2-MemberNamesCheck.rst new file mode 100644 index 0000000..4ae8699 --- /dev/null +++ b/docs/clang-tidy/checks/aliceO2-MemberNamesCheck.rst @@ -0,0 +1,17 @@ +.. title:: clang-tidy - aliceO2-members-name + +aliceO2-members-name +============ + +Namespace names follow underscore convention and start with a lower case letter: my_namespace. + +Additional Info: + +namespace my_namespace +{ + +void MyClass::doSomething() +{ + ... +} +} diff --git a/docs/clang-tidy/checks/aliceO2-SizeofCheck.rst b/docs/clang-tidy/checks/aliceO2-SizeofCheck.rst new file mode 100644 index 0000000..2357e63 --- /dev/null +++ b/docs/clang-tidy/checks/aliceO2-SizeofCheck.rst @@ -0,0 +1,6 @@ +.. title:: clang-tidy - aliceO2-SizeOf + +aliceO2-SizeOf +============ + +FIXME: Describe what patterns does the check detect and why. Give examples. diff --git a/docs/clang-tidy/checks/aliceO2-namespace-naming.rst b/docs/clang-tidy/checks/aliceO2-namespace-naming.rst new file mode 100644 index 0000000..d2c4093 --- /dev/null +++ b/docs/clang-tidy/checks/aliceO2-namespace-naming.rst @@ -0,0 +1,6 @@ +.. title:: clang-tidy - aliceO2-namespace-naming + +aliceO2-namespace-naming +======================== + +FIXME: Describe what patterns does the check detect and why. Give examples. diff --git a/docs/clang-tidy/checks/list.rst b/docs/clang-tidy/checks/list.rst new file mode 100644 index 0000000..b29d297 --- /dev/null +++ b/docs/clang-tidy/checks/list.rst @@ -0,0 +1,9 @@ +.. title:: clang-tidy - Clang-Tidy Checks + +Clang-Tidy Checks +========================= + +.. toctree:: + aliceO2-MemberNamesCheck + aliceO2-SizeofCheck + aliceO2-namespace-naming 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 64a2a5d..0000000 --- a/plugin/PluginTidyModule.cpp +++ /dev/null @@ -1,48 +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 "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 AliceO2TidyModule using this statically initialized variable. -static ClangTidyModuleRegistry::Add -X("aliceO2-module", "Adds AliceO2 specific checks"); - -// This anchor is used to force the linker to link in the generated object file -// and thus register the AliceO2Module. -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/test/.clang-tidy b/test/.clang-tidy new file mode 100644 index 0000000..52f91c9 --- /dev/null +++ b/test/.clang-tidy @@ -0,0 +1,3 @@ +CheckOptions: + - key: CheckPathRegex + value: '.*/test/.*' diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index eabea68..53c4a03 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -2,5 +2,17 @@ add_executable(testregex testregex.cpp) add_test(testregexcorrect testregex) +# we need the FileCheck program in order to execute the check_clang_tidy.py script +find_program(LLVMFILECHECK FileCheck HINTS PATH) +if (LLVMFILECHECK) + +# testing namespace naming checker +# add_test(NAME aliceo2namespace COMMAND +# ${CMAKE_SOURCE_DIR}/check_clang_tidy.py +# ${CMAKE_SOURCE_DIR}/test/aliceO2-namespace-naming.cpp +# aliceO2-namespace-naming ${CMAKE_BINARY_DIR}/tool/O2codecheck) + +else() + message(STATUS "FileCheck not found; disabling the check_clang_tidy unit tests\n") +endif(LLVMFILECHECK) -# correctness testing of checks diff --git a/test/aliceO2-namespace-naming.cpp b/test/aliceO2-namespace-naming.cpp new file mode 100644 index 0000000..4452312 --- /dev/null +++ b/test/aliceO2-namespace-naming.cpp @@ -0,0 +1,218 @@ +// RUN: %check_clang_tidy %s aliceO2-namespace-naming %t + +namespace {} +namespace{ +} +namespace +{ +namespace simple +{ +}; +}; + +namespace o2 +{ +} +namespace o2codecheck +{ +} +namespace a_1234_5678_b +{ +} + +namespace TPC +// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: namespace 'TPC' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}}namespace tpc{{$}} +{ +} + +using namespace TPC; +// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: namespace 'TPC' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}}using namespace tpc;{{$}} + +namespace OuterNamespaceWrong +// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: namespace 'OuterNamespaceWrong' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}}namespace outer_namespace_wrong{{$}} +{ +namespace InnerNamespaceWrong +// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: namespace 'InnerNamespaceWrong' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}}namespace inner_namespace_wrong{{$}} +{ +class InnerClass +{ +public: + int a; +}; +}; +}; + +namespace outer_namespace_correct +{ +namespace inner_namespace_correct +{ +class InnerClass +{ +public: + int b; +}; +}; +}; + +using namespace OuterNamespaceWrong::InnerNamespaceWrong; +// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: namespace 'OuterNamespaceWrong' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-MESSAGES: :[[@LINE-2]]:38: warning: namespace 'InnerNamespaceWrong' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}}using namespace outer_namespace_wrong::inner_namespace_wrong;{{$}} +using namespace outer_namespace_correct::inner_namespace_correct; + +typedef OuterNamespaceWrong::InnerNamespaceWrong::InnerClass JustInnerClass1; +// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: namespace 'OuterNamespaceWrong' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-MESSAGES: :[[@LINE-2]]:30: warning: namespace 'InnerNamespaceWrong' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}}typedef outer_namespace_wrong::inner_namespace_wrong::InnerClass JustInnerClass1;{{$}} +typedef outer_namespace_correct::inner_namespace_correct::InnerClass JustInnerClass2; + +namespace FirstNamespace +// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: namespace 'FirstNamespace' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}}namespace first_namespace{{$}} +{ + int a; + void fooFromNamespace(); + + void bar() + { + } + + class NamespaceClassForLaterDefinition; + + class NamespaceClass + { + static int c1; + public: + static int bb; + static int getC1(); + int getC1NotStatic(); + + class NamespaceClassInnerClass + { + int c2; + public: + int c3; + static int c4; + + static int getC2(); + int getC2NotStatic(); + + void dummy1() + { + NamespaceClass::bb=2; + } + }; + }; +}; + +class FirstNamespace::NamespaceClassForLaterDefinition +// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: namespace 'FirstNamespace' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}}class first_namespace::NamespaceClassForLaterDefinition{{$}} +{ +int justSomething; +}; + +namespace Singleword +// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: namespace 'Singleword' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}}namespace singleword{{$}} +{ +}; + +namespace Double_Words +// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: namespace 'Double_Words' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}}namespace double_words{{$}} +{ +}; + +namespace secondNamespace +// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: namespace 'secondNamespace' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}}namespace second_namespace{{$}} +{ + int b; +}; + +class FirstClass +{ +int fooVar; +public: + void fooFromClass(); +}; + +struct FirstStruct +{ +int fooVar; +public: + void fooFromStruct(); +}; + +int FirstNamespace::NamespaceClass::getC1() +// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: namespace 'FirstNamespace' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}}int first_namespace::NamespaceClass::getC1(){{$}} +{ + return c1; +} + +void FirstClass::fooFromClass() +{ +} + +void FirstStruct::fooFromStruct() +{ +} + +void FirstNamespace::fooFromNamespace(); // just forward declaration +// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: namespace 'FirstNamespace' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}}void first_namespace::fooFromNamespace(); // just forward declaration{{$}} + +void FirstNamespace::fooFromNamespace() // definition +// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: namespace 'FirstNamespace' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}}void first_namespace::fooFromNamespace() // definition{{$}} +{ +} + +void dummy1(int par1) +{ +} + +int main() +{ + FirstNamespace::a=5; +// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: namespace 'FirstNamespace' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}} first_namespace::a=5;{{$}} + + dummy1(FirstNamespace::a); +// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: namespace 'FirstNamespace' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}} dummy1(first_namespace::a);{{$}} + + int temp = FirstNamespace::NamespaceClass::getC1(); +// CHECK-MESSAGES: :[[@LINE-1]]:14: warning: namespace 'FirstNamespace' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}} int temp = first_namespace::NamespaceClass::getC1();{{$}} + FirstNamespace::NamespaceClass classInstance; +// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: namespace 'FirstNamespace' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}} first_namespace::NamespaceClass classInstance;{{$}} + temp = classInstance.getC1NotStatic(); + + temp = FirstNamespace::NamespaceClass::NamespaceClassInnerClass::getC2(); +// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: namespace 'FirstNamespace' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}} temp = first_namespace::NamespaceClass::NamespaceClassInnerClass::getC2();{{$}} + FirstNamespace::NamespaceClass::NamespaceClassInnerClass classInstance2; +// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: namespace 'FirstNamespace' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}} first_namespace::NamespaceClass::NamespaceClassInnerClass classInstance2;{{$}} + temp = classInstance2.getC2NotStatic(); + + temp = classInstance2.c3; + temp = FirstNamespace::NamespaceClass::NamespaceClassInnerClass::c4; +// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: namespace 'FirstNamespace' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}} temp = first_namespace::NamespaceClass::NamespaceClassInnerClass::c4;{{$}} + + secondNamespace::b=166; +// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: namespace 'secondNamespace' does not follow the underscore convention [aliceO2-namespace-naming] +// CHECK-FIXES: {{^}} second_namespace::b=166;{{$}} + + return 0; +} + diff --git a/test/clear_test_results.sh b/test/clear_test_results.sh new file mode 100755 index 0000000..084ee7c --- /dev/null +++ b/test/clear_test_results.sh @@ -0,0 +1,3 @@ +rm *_result.cpp +rm *_result.cpp.msg +rm *_result.cpp.orig diff --git a/tool/CMakeLists.txt b/tool/CMakeLists.txt index e11d5a2..ae6622f 100644 --- a/tool/CMakeLists.txt +++ b/tool/CMakeLists.txt @@ -1,50 +1 @@ -set(LLVM_LINK_COMPONENTS - support - ) - -add_clang_executable(O2codecheck - ClangTidyMain.cpp - ) - -target_link_libraries(O2codecheck - clangAST - clangASTMatchers - clangBasic - clangTidy - - # link our own checks - clangTidyAliceO2Module - clangTidyReportingModule - - # include checkers available from main clang-tidy - clangTidyBoostModule - clangTidyCERTModule - clangTidyCppCoreGuidelinesModule - clangTidyGoogleModule - clangTidyLLVMModule - clangTidyMiscModule - clangTidyModernizeModule - clangTidyPerformanceModule - clangTidyReadabilityModule - - clangTooling - ) - -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 52fc374..0000000 --- a/tool/ClangTidyMain.cpp +++ /dev/null @@ -1,483 +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" - -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: '' - AnalyzeTemporaryDtors: false - User: user - CheckOptions: - - key: some-check.SomeOption - value: 'some value' - ... - -)"); - -const char DefaultChecks[] = // Enable these checks: - "clang-diagnostic-*," // * compiler diagnostics - "clang-analyzer-*," // * Static Analyzer checks - "-clang-analyzer-alpha*"; // * but not alpha checks: many false positives - -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 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 AnalyzeTemporaryDtors("analyze-temporary-dtors", - cl::desc(R"( -Enable temporary destructor-aware analysis in -clang-analyzer- checks. -This option overrides the value read from a -.clang-tidy file. -)"), - cl::init(false), - 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 sorce -code with clang-apply-replacements. -)"), - 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 void printProfileData(const ProfileData &Profile, - llvm::raw_ostream &OS) { - // Time is first to allow for sorting by it. - std::vector> Timers; - TimeRecord Total; - - for (const auto& P : Profile.Records) { - Timers.emplace_back(P.getValue(), P.getKey()); - Total += P.getValue(); - } - - std::sort(Timers.begin(), Timers.end()); - - std::string Line = "===" + std::string(73, '-') + "===\n"; - OS << Line; - - if (Total.getUserTime()) - OS << " ---User Time---"; - if (Total.getSystemTime()) - OS << " --System Time--"; - if (Total.getProcessTime()) - OS << " --User+System--"; - OS << " ---Wall Time---"; - if (Total.getMemUsed()) - OS << " ---Mem---"; - OS << " --- Name ---\n"; - - // Loop through all of the timing data, printing it out. - for (auto I = Timers.rbegin(), E = Timers.rend(); I != E; ++I) { - I->first.print(Total, OS); - OS << I->second << '\n'; - } - - Total.print(Total, OS); - OS << "Total\n"; - OS << Line << "\n"; - OS.flush(); -} - -static std::unique_ptr createOptionsProvider() { - 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.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors; - 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 (AnalyzeTemporaryDtors.getNumOccurrences() > 0) - OverrideOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors; - - 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); -} - -static int clangTidyMain(int argc, const char **argv) { - CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory, - cl::ZeroOrMore); - - auto OptionsProvider = createOptionsProvider(); - if (!OptionsProvider) - return 1; - - StringRef FileName("dummy"); - auto PathList = OptionsParser.getSourcePathList(); - if (!PathList.empty()) { - FileName = PathList.front(); - } - - SmallString<256> FilePath(FileName); - if (std::error_code EC = llvm::sys::fs::make_absolute(FilePath)) { - llvm::errs() << "Can't make absolute path from " << FileName << ": " - << EC.message() << "\n"; - } - ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FilePath); - std::vector EnabledChecks = getCheckNames(EffectiveOptions); - - 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); - 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; - } - - ProfileData Profile; - - std::vector Errors; - ClangTidyStats Stats = - runClangTidy(std::move(OptionsProvider), OptionsParser.getCompilations(), - PathList, &Errors, - EnableCheckProfile ? &Profile : nullptr); - bool FoundErrors = - std::find_if(Errors.begin(), Errors.end(), [](const ClangTidyError &E) { - return E.DiagLevel == ClangTidyError::Error; - }) != Errors.end(); - - const bool DisableFixes = Fix && FoundErrors && !FixErrors; - - unsigned WErrorCount = 0; - - // -fix-errors implies -fix. - handleErrors(Errors, (FixErrors || Fix) && !DisableFixes, WErrorCount); - - 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(Errors, OS); - } - - printStats(Stats); - if (DisableFixes) - llvm::errs() - << "Found compiler errors, but -fix-errors was not specified.\n" - "Fixes have NOT been applied.\n\n"; - - if (EnableCheckProfile) - printProfileData(Profile, llvm::errs()); - - if (WErrorCount) { - StringRef Plural = WErrorCount == 1 ? "" : "s"; - llvm::errs() << WErrorCount << " warning" << Plural << " treated as error" - << Plural << "\n"; - return WErrorCount; - } - - // return error code when errors found - return Errors.size(); -} - -// 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 BoostModule. -extern volatile int BoostModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED BoostModuleAnchorDestination = - BoostModuleAnchorSource; - -// 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 GoogleModule. -extern volatile int GoogleModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED GoogleModuleAnchorDestination = - GoogleModuleAnchorSource; - -// 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 PerformanceModule. -extern volatile int PerformanceModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED PerformanceModuleAnchorDestination = - PerformanceModuleAnchorSource; - -// 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 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..96e87fe 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 @@ -95,14 +102,20 @@ def apply_fixes(args, tmpdir): shutil.rmtree(tmpdir) -def run_tidy(args, tmpdir, build_path, queue): +def run_tidy(args, tmpdir, build_path, queue, lock): """Takes filenames out of queue and runs clang-tidy on them.""" 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) - sys.stdout.write(' '.join(invocation) + '\n') - subprocess.call(invocation) + tmpdir, build_path, args.header_filter, args.config, args.extra_args) + proc = subprocess.Popen(invocation, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + output = proc.communicate()[0] + # Print the command and its output in one piece; concurrent writes to sys.stdout + # from several threads can corrupt it (e.g. NUL bytes with Python 3.9/3.10). + with lock: + sys.stdout.write(' '.join(invocation) + '\n') + sys.stdout.write(output.decode('utf-8', 'replace')) + sys.stdout.flush() queue.task_done() @@ -126,6 +139,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 +158,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 +175,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. @@ -181,9 +198,10 @@ def main(): try: # Spin up a bunch of tidy-launching threads. queue = Queue.Queue(max_task) + lock = threading.Lock() for _ in range(max_task): t = threading.Thread(target=run_tidy, - args=(args, tmpdir, build_path, queue)) + args=(args, tmpdir, build_path, queue, lock)) t.daemon = True t.start() @@ -198,13 +216,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/CMakeLists.txt b/utility/CMakeLists.txt new file mode 100644 index 0000000..c703cc2 --- /dev/null +++ b/utility/CMakeLists.txt @@ -0,0 +1,2 @@ + +install(PROGRAMS ThinCompilationsDatabase.py DESTINATION bin) diff --git a/utility/ThinCompilationsDatabase.py b/utility/ThinCompilationsDatabase.py new file mode 100755 index 0000000..e83b21a --- /dev/null +++ b/utility/ThinCompilationsDatabase.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python + +# A python script with the goal +# to transform a (large) compilations database +# to a smaller compilations database, given a list of source files +# that have changed (currently only supporting c++ source and header files). +# This should be useful to reduce the time spent in static code analysis by only +# checking files that have changed, or are influenced by a change. +# +# 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 +try: + import Queue +except ImportError: + import queue as Queue +import threading +import multiprocessing +import time +import sys + +verbosity=0 + +def parseArgs(): + """ Setup + Parse arguments from command line; return a parse object """ + parser = argparse.ArgumentParser(description='Runs over all entries in a ' + 'compilation database. Produces a filtered/thinned version of it.') + parser.add_argument('-j', type=int, default=0, + help='Number of threads to be used for processing. In any case,' + 'not more that the number of available CPU threads will be used (which is the default).') + parser.add_argument('-use-files', default=None, + help='\':\' separated file list used to thin out the database. Usually a list of header and source files.' + '\n If no files are given, the default behaviour is to run over the complete database and filter out' + 'only ROOT dictionary files and Protobuf generated files.') + parser.add_argument('-exclude-files', default=None, + help='A regular expression telling which files to exclude from the database. Takes precedence over \'-use-files\'.') + parser.add_argument('-o', default='thinned_compile_commands.json', + help='Filename of output compilations database. [default: thinned_compile_commands.json]') + parser.add_argument('--verbose', type=int, default=0, + help='Display verbose information about what is going on') + return parser.parse_args() + +def verboseLog(string, level=0): + global verbosity + if verbosity > 0: + print(string) + +def getListOfChangedFiles(colonseparatedfilepaths): + """ processes the argument '-use-files' and returns a python list of filenames """ + return colonseparatedfilepaths.split(":") + +def makeInvalidClosure(args): + regex = None + if args.exclude_files: + regex=re.compile(args.exclude_files) + def f(filename): + return regex.match(filename) is not None if regex else None + return f + +def isHeaderFile(filename): + # make this more general + expression=".*\.h" + # make this more efficient by compiling the expression + return re.match(expression, filename) is not None + +def isSourceFile(filename): + # make this more general + expression=".*\.cxx" + # make this more efficient by compiling the expression + return re.match(expression, filename) is not None + +# modifies a compilation command by appending -MM (and removing the -o flag) +# in order to retrieve the header dependencies +def modifyCompileCommand(command): + newcommand=[] + outputflagseen=False + # take out the output command + for token in command.split(' '): + if len(token)==0: + continue + if token=='-o': + outputflagseen=True; + else: + if not outputflagseen: + newcommand.append(token) + else: + outputflagseen=False + # add the -MM flag which will generate the header dependency list for a source file + newcommand.append('-MM') + return newcommand + +def matchesHeader(line, header): + expression=".*\.h" + # make this more efficient by compiling the expression + 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: + 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 +def processItem(keepalive, changedheaderlist, queue, outqueue): + while len(keepalive) > 0: + try: + # this operation is blocking for at most 0.5 seconds + # sad hack to be able to check whether we want this thread to be kept alive + # unfortunately, the main process never exits otherwise + entry = queue.get(True, 0.5) + includedheaderlist=queryListOfHeaders(modifyCompileCommand(entry['command'])) + for header in changedheaderlist: + for include in includedheaderlist: + expression=".*"+header + matches = re.match(expression, include) + if not matches == None: + verboseLog("Adding " + entry['file'] + " because of a dependence on a modified header") + outqueue.put(entry) + continue + + queue.task_done() + except Queue.Empty: + pass + +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())) + time.sleep(1) + +#custom function to remove duplicates and return a new list +#set() cannot be used since the entries are not hashable +def removeDuplicates(inputlist): + outputlist=[] + for e in inputlist: + if e not in outputlist: + outputlist.append(e) + return outputlist + + +def fileMatchesAnyInSourceFileList(filename, sourcefilelist): + '''returns true if any filename in sourcefilelist matches + filename + + items in sourcefilelist will have only paths relativ (to + a git repository); while filename is a fully qualified path + ''' + # TODO: item should be at end of filename + for item in sourcefilelist: + if item in filename: + return True + return False + +# +# THE MAIN FUNCTION +# +def main(): + checkall=False + listofchangedfiles=[] + args = parseArgs() + global verbosity + verbosity = args.verbose + if not args.use_files: + verboseLog("no changeset given ... putting all (modulo the exclude set)") + checkall=True + else: + listofchangedfiles=getListOfChangedFiles(args.use_files) + + #setup the isInvalid (closure) function + isInvalid=makeInvalidClosure(args) + + #open the compilations database + try: + file=open('compile_commands.json').read() + except IOError: + print("Problem opening the compilation database (file not found)") + sys.exit(1) + + #convert json to dict + data=json.loads(file); + + #make 2 lists, changedheaders and changedsourcefiles + changedheaderlist=[] + changedsourcefilelist=[] + for file in listofchangedfiles: + if isHeaderFile(file): + changedheaderlist.append(file) + elif isSourceFile(file): + changedsourcefilelist.append(file) + + # make input/output queues for multithreaded processing + inputqueue = Queue.Queue() + outputqueue = Queue.Queue() + keepAlive=['alive'] + + # make some servicing threads + max_task = multiprocessing.cpu_count() + if args.j: + if args.j>0: + max_task = max(max_task,j) + + verboseLog("processing with " + str(max_task) + " threads.") + for _ in range(max_task): + t = threading.Thread(target=processItem, args=(keepAlive,changedheaderlist,inputqueue,outputqueue)) + t.deamon=True + t.start() + + # launch the reporting thread + rt = threading.Thread(target=reportProgress, args=(keepAlive,inputqueue,outputqueue)) + rt.deamon=True + rt.start() + + outputdict=[] + #scan through compile database and filter against files + verboseLog("Processing " + str(len(data)) + " items.") + for entry in data: + filename=entry['file'] + basename=os.path.basename(filename) + + # check if invalid anyway + if (isInvalid(basename)): + verboseLog("Excluding " + basename + " because of exclude filter") + continue + + # check if this entry is part of the changed source file list + # if yes, continue directly + if checkall==True or fileMatchesAnyInSourceFileList(filename, changedsourcefilelist): + verboseLog("Adding " + entry['file'] + " because of presence in modify list (or lack thereof)") + outputqueue.put(entry) + continue + + if len(changedheaderlist) > 0: + # otherwise check if this source file is influenced by some changed header file + # TODO: if the header does not contain a template, it might be enough + # to only add one single source files that depends on it???? + inputqueue.put(entry) + + # wait on the queue --> wait until queue is completely empty + inputqueue.join() + # now we can shut down the deamon threads + keepAlive[:]=[] + + #put outputqueue into outputdict + while outputqueue.qsize() > 0: + outputdict.append(outputqueue.get(False)) + + # write result dictionary to json + outjson = json.dumps(removeDuplicates(outputdict), sort_keys=True, indent=4, separators=(',', ': ')) + with open(args.o,'w') as fp: + fp.write(outjson) + + return + +if __name__ == '__main__': + main()