diff --git a/CMakeLists.txt b/CMakeLists.txt index ff1ac6c..ff3e144 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,7 +14,7 @@ if( CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR ) # find clang + llvm - find_package(Clang REQUIRED) + find_package(Clang REQUIRED CONFIG) if( LLVM_FOUND ) list(APPEND CMAKE_MODULE_PATH "${LLVM_CMAKE_DIR}") diff --git a/ClangTidy.h b/ClangTidy.h deleted file mode 100644 index 51d9e22..0000000 --- a/ClangTidy.h +++ /dev/null @@ -1,125 +0,0 @@ -//===--- ClangTidy.h - clang-tidy -------------------------------*- C++ -*-===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// - -#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 "llvm/ADT/StringSet.h" -#include -#include - -namespace llvm { -class raw_ostream; -} // namespace llvm - -namespace clang { - -class ASTConsumer; -class CompilerInstance; -namespace tooling { -class CompilationDatabase; -} // namespace tooling - -namespace tidy { - -class ClangTidyCheckFactories; - -class ClangTidyASTConsumerFactory { -public: - ClangTidyASTConsumerFactory( - ClangTidyContext &Context, - IntrusiveRefCntPtr OverlayFS = nullptr); - - /// Returns an ASTConsumer that runs the specified clang-tidy checks. - std::unique_ptr - createASTConsumer(clang::CompilerInstance &Compiler, StringRef File); - - /// Get the list of enabled checks. - std::vector getCheckNames(); - - /// Get the union of options from all checks. - ClangTidyOptions::OptionMap getCheckOptions(); - -private: - ClangTidyContext &Context; - IntrusiveRefCntPtr OverlayFS; - std::unique_ptr CheckFactories; -}; - -/// Fills the list of check names that are enabled when the provided -/// filters are applied. -std::vector getCheckNames(const ClangTidyOptions &Options, - bool AllowEnablingAnalyzerAlphaCheckers); - -struct NamesAndOptions { - llvm::StringSet<> Names; - llvm::StringSet<> Options; -}; - -NamesAndOptions -getAllChecksAndOptions(bool AllowEnablingAnalyzerAlphaCheckers = true); - -/// Returns the effective check-specific options. -/// -/// The method configures ClangTidy with the specified \p Options and collects -/// effective options from all created checks. The returned set of options -/// includes default check-specific options for all keys not overridden by \p -/// Options. -ClangTidyOptions::OptionMap -getCheckOptions(const ClangTidyOptions &Options, - bool AllowEnablingAnalyzerAlphaCheckers); - -/// Run a set of clang-tidy checks on a set of files. -/// -/// \param EnableCheckProfile If provided, it enables check profile collection -/// in MatchFinder, and will contain the result of the profile. -/// \param StoreCheckProfile If provided, and EnableCheckProfile is true, -/// the profile will not be output to stderr, but will instead be stored -/// as a JSON file in the specified directory. -std::vector -runClangTidy(clang::tidy::ClangTidyContext &Context, - const tooling::CompilationDatabase &Compilations, - ArrayRef InputFiles, - llvm::IntrusiveRefCntPtr BaseFS, - bool ApplyAnyFix, bool EnableCheckProfile = false, - llvm::StringRef StoreCheckProfile = StringRef()); - -/// Controls what kind of fixes clang-tidy is allowed to apply. -enum FixBehaviour { - /// Don't try to apply any fix. - FB_NoFix, - /// Only apply fixes added to warnings. - FB_Fix, - /// Apply fixes found in notes. - FB_FixNotes -}; - -// FIXME: This interface will need to be significantly extended to be useful. -// FIXME: Implement confidence levels for displaying/fixing errors. -// -/// Displays the found \p Errors to the users. If \p Fix is \ref FB_Fix or \ref -/// FB_FixNotes, \p Errors containing fixes are automatically applied and -/// reformatted. If no clang-format configuration file is found, the given \P -/// FormatStyle is used. -void handleErrors(llvm::ArrayRef Errors, - ClangTidyContext &Context, FixBehaviour Fix, - unsigned &WarningsAsErrorsCount, - llvm::IntrusiveRefCntPtr BaseFS); - -/// Serializes replacements into YAML and writes them to the specified -/// output stream. -void exportReplacements(StringRef MainFilePath, - const std::vector &Errors, - raw_ostream &OS); - -} // end namespace tidy -} // end namespace clang - -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDY_H diff --git a/ClangTidyCheck.h b/ClangTidyCheck.h deleted file mode 100644 index 656a2f0..0000000 --- a/ClangTidyCheck.h +++ /dev/null @@ -1,533 +0,0 @@ -//===--- ClangTidyCheck.h - clang-tidy --------------------------*- C++ -*-===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYCHECK_H -#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYCHECK_H - -#include "ClangTidyDiagnosticConsumer.h" -#include "ClangTidyOptions.h" -#include "clang/ASTMatchers/ASTMatchFinder.h" -#include "clang/Basic/Diagnostic.h" -#include -#include -#include -#include - -namespace clang { - -class SourceManager; - -namespace tidy { - -/// This class should be specialized by any enum type that needs to be converted -/// to and from an \ref llvm::StringRef. -template struct OptionEnumMapping { - // Specializations of this struct must implement this function. - static ArrayRef> getEnumMapping() = delete; -}; - -/// 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: - /// 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); - - /// Override this to disable registering matchers and PP callbacks if an - /// invalid language version is being used. - /// - /// For example if a check is examining overloaded functions then this should - /// be overridden to return false when the CPlusPlus flag is not set in - /// \p LangOpts. - virtual bool isLanguageVersionSupported(const LangOptions &LangOpts) const { - return true; - } - - /// Override this to register ``PPCallbacks`` in the preprocessor. - /// - /// This should be used for clang-tidy checks that analyze preprocessor- - /// dependent properties, e.g. include directives and macro definitions. - /// - /// This will only be executed if the function isLanguageVersionSupported - /// returns true. - /// - /// There are two Preprocessors to choose from that differ in how they handle - /// modular #includes: - /// - PP is the real Preprocessor. It doesn't walk into modular #includes and - /// thus doesn't generate PPCallbacks for their contents. - /// - ModuleExpanderPP preprocesses the whole translation unit in the - /// non-modular mode, which allows it to generate PPCallbacks not only for - /// the main file and textual headers, but also for all transitively - /// included modular headers when the analysis runs with modules enabled. - /// When modules are not enabled ModuleExpanderPP just points to the real - /// preprocessor. - virtual void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, - Preprocessor *ModuleExpanderPP) {} - - /// 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. - /// - /// This will only be executed if the function isLanguageVersionSupported - /// returns true. - /// - /// 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) {} - - /// ``ClangTidyChecks`` that register ASTMatchers should do the actual - /// work in here. - virtual void check(const ast_matchers::MatchFinder::MatchResult &Result) {} - - /// Add a diagnostic with the check's name. - DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, - DiagnosticIDs::Level Level = DiagnosticIDs::Warning); - - /// Add a diagnostic with the check's name. - DiagnosticBuilder diag(StringRef Description, - DiagnosticIDs::Level Level = DiagnosticIDs::Warning); - - /// Adds a diagnostic to report errors in the check's configuration. - DiagnosticBuilder - configurationDiag(StringRef Description, - DiagnosticIDs::Level Level = DiagnosticIDs::Warning) const; - - /// 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) {} - - /// 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 { - void diagnoseBadIntegerOption(const Twine &Lookup, - StringRef Unparsed) const; - void diagnoseBadBooleanOption(const Twine &Lookup, - StringRef Unparsed) const; - void diagnoseBadEnumOption(const Twine &Lookup, StringRef Unparsed, - StringRef Suggestion = StringRef()) const; - - public: - /// Initializes the instance using \p CheckName + "." as a prefix. - OptionsView(StringRef CheckName, - const ClangTidyOptions::OptionMap &CheckOptions, - ClangTidyContext *Context); - - /// 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, return - /// ``std::nullopt``. - std::optional get(StringRef LocalName) const; - - /// 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. - StringRef get(StringRef LocalName, StringRef Default) const; - - /// 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, return ``std::nullopt``. - std::optional getLocalOrGlobal(StringRef LocalName) const; - - /// 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 \p Default. - StringRef getLocalOrGlobal(StringRef LocalName, StringRef Default) const; - - /// 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, - /// return ``std::nullopt``. - /// - /// If the corresponding key can't be parsed as a ``T``, emit a - /// diagnostic and return ``std::nullopt``. - template - std::enable_if_t, std::optional> - get(StringRef LocalName) const { - if (std::optional Value = get(LocalName)) { - T Result{}; - if (!StringRef(*Value).getAsInteger(10, Result)) - return Result; - diagnoseBadIntegerOption(NamePrefix + LocalName, *Value); - } - return std::nullopt; - } - - /// 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 `none`, `null`, - /// `-1` or empty, return ``std::nullopt``. If the corresponding - /// key is not present, return \p Default. - /// - /// If the corresponding key can't be parsed as a ``T``, emit a - /// diagnostic and return \p Default. - template - std::enable_if_t, std::optional> - get(StringRef LocalName, std::optional Default) const { - if (std::optional Value = get(LocalName)) { - if (Value == "" || Value == "none" || Value == "null" || - (std::is_unsigned_v && Value == "-1")) - return std::nullopt; - T Result{}; - if (!StringRef(*Value).getAsInteger(10, Result)) - return Result; - diagnoseBadIntegerOption(NamePrefix + LocalName, *Value); - } - return Default; - } - - /// 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, return - /// \p Default. - /// - /// If the corresponding key can't be parsed as a ``T``, emit a - /// diagnostic and return \p Default. - template - std::enable_if_t, T> get(StringRef LocalName, - T Default) const { - return get(LocalName).value_or(Default); - } - - /// Read a named option from the ``Context`` and parse it as an - /// integral type ``T``. - /// - /// Reads the option with the check-local name \p LocalName from local or - /// global ``CheckOptions``. Gets local option first. If local is not - /// present, falls back to get global option. If global option is not - /// present either, return ``std::nullopt``. - /// - /// If the corresponding key can't be parsed as a ``T``, emit a - /// diagnostic and return ``std::nullopt``. - template - std::enable_if_t, std::optional> - getLocalOrGlobal(StringRef LocalName) const { - std::optional ValueOr = get(LocalName); - bool IsGlobal = false; - if (!ValueOr) { - IsGlobal = true; - ValueOr = getLocalOrGlobal(LocalName); - if (!ValueOr) - return std::nullopt; - } - T Result{}; - if (!StringRef(*ValueOr).getAsInteger(10, Result)) - return Result; - diagnoseBadIntegerOption( - IsGlobal ? Twine(LocalName) : NamePrefix + LocalName, *ValueOr); - return std::nullopt; - } - - /// Read a named option from the ``Context`` and parse it as an - /// integral type ``T``. - /// - /// Reads the option with the check-local name \p LocalName from local or - /// global ``CheckOptions``. Gets local option first. If local is not - /// present, falls back to get global option. If global option is not - /// present either, return \p Default. If the value value was found - /// and equals ``none``, ``null``, ``-1`` or empty, return ``std::nullopt``. - /// - /// If the corresponding key can't be parsed as a ``T``, emit a - /// diagnostic and return \p Default. - template - std::enable_if_t, std::optional> - getLocalOrGlobal(StringRef LocalName, std::optional Default) const { - std::optional ValueOr = get(LocalName); - bool IsGlobal = false; - if (!ValueOr) { - IsGlobal = true; - ValueOr = getLocalOrGlobal(LocalName); - if (!ValueOr) - return Default; - } - T Result{}; - if (ValueOr == "" || ValueOr == "none" || ValueOr == "null" || - (std::is_unsigned_v && ValueOr == "-1")) - return std::nullopt; - if (!StringRef(*ValueOr).getAsInteger(10, Result)) - return Result; - diagnoseBadIntegerOption( - IsGlobal ? Twine(LocalName) : NamePrefix + LocalName, *ValueOr); - return Default; - } - - /// Read a named option from the ``Context`` and parse it as an - /// integral type ``T``. - /// - /// Reads the option with the check-local name \p LocalName from local or - /// global ``CheckOptions``. Gets local option first. If local is not - /// present, falls back to get global option. If global option is not - /// present either, return \p Default. - /// - /// If the corresponding key can't be parsed as a ``T``, emit a - /// diagnostic and return \p Default. - template - std::enable_if_t, T> - getLocalOrGlobal(StringRef LocalName, T Default) const { - return getLocalOrGlobal(LocalName).value_or(Default); - } - - /// Read a named option from the ``Context`` and parse it as an - /// enum type ``T``. - /// - /// Reads the option with the check-local name \p LocalName from the - /// ``CheckOptions``. If the corresponding key is not present, return - /// ``std::nullopt``. - /// - /// If the corresponding key can't be parsed as a ``T``, emit a - /// diagnostic and return ``std::nullopt``. - /// - /// \ref clang::tidy::OptionEnumMapping must be specialized for ``T`` to - /// supply the mapping required to convert between ``T`` and a string. - template - std::enable_if_t, std::optional> - get(StringRef LocalName, bool IgnoreCase = false) const { - if (std::optional ValueOr = - getEnumInt(LocalName, typeEraseMapping(), false, IgnoreCase)) - return static_cast(*ValueOr); - return std::nullopt; - } - - /// Read a named option from the ``Context`` and parse it as an - /// enum type ``T``. - /// - /// Reads the option with the check-local name \p LocalName from the - /// ``CheckOptions``. If the corresponding key is not present, - /// return \p Default. - /// - /// If the corresponding key can't be parsed as a ``T``, emit a - /// diagnostic and return \p Default. - /// - /// \ref clang::tidy::OptionEnumMapping must be specialized for ``T`` to - /// supply the mapping required to convert between ``T`` and a string. - template - std::enable_if_t, T> get(StringRef LocalName, T Default, - bool IgnoreCase = false) const { - return get(LocalName, IgnoreCase).value_or(Default); - } - - /// Read a named option from the ``Context`` and parse it as an - /// enum type ``T``. - /// - /// Reads the option with the check-local name \p LocalName from local or - /// global ``CheckOptions``. Gets local option first. If local is not - /// present, falls back to get global option. If global option is not - /// present either, returns ``std::nullopt``. - /// - /// If the corresponding key can't be parsed as a ``T``, emit a - /// diagnostic and return ``std::nullopt``. - /// - /// \ref clang::tidy::OptionEnumMapping must be specialized for ``T`` to - /// supply the mapping required to convert between ``T`` and a string. - template - std::enable_if_t, std::optional> - getLocalOrGlobal(StringRef LocalName, bool IgnoreCase = false) const { - if (std::optional ValueOr = - getEnumInt(LocalName, typeEraseMapping(), true, IgnoreCase)) - return static_cast(*ValueOr); - return std::nullopt; - } - - /// Read a named option from the ``Context`` and parse it as an - /// enum type ``T``. - /// - /// Reads the option with the check-local name \p LocalName from local or - /// global ``CheckOptions``. Gets local option first. If local is not - /// present, falls back to get global option. If global option is not - /// present either return \p Default. - /// - /// If the corresponding key can't be parsed as a ``T``, emit a - /// diagnostic and return \p Default. - /// - /// \ref clang::tidy::OptionEnumMapping must be specialized for ``T`` to - /// supply the mapping required to convert between ``T`` and a string. - template - std::enable_if_t, T> - getLocalOrGlobal(StringRef LocalName, T Default, - bool IgnoreCase = false) const { - return getLocalOrGlobal(LocalName, IgnoreCase).value_or(Default); - } - - /// 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; - - /// Stores an option with the check-local name \p LocalName with - /// integer value \p Value to \p Options. - template - std::enable_if_t> - store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, - T Value) const { - storeInt(Options, LocalName, Value); - } - - /// Stores an option with the check-local name \p LocalName with - /// integer value \p Value to \p Options. If the value is empty - /// stores `` - template - std::enable_if_t> - store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, - std::optional Value) const { - if (Value) - storeInt(Options, LocalName, *Value); - else - store(Options, LocalName, "none"); - } - - /// Stores an option with the check-local name \p LocalName as the string - /// representation of the Enum \p Value to \p Options. - /// - /// \ref clang::tidy::OptionEnumMapping must be specialized for ``T`` to - /// supply the mapping required to convert between ``T`` and a string. - template - std::enable_if_t> - store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, - T Value) const { - ArrayRef> Mapping = - OptionEnumMapping::getEnumMapping(); - auto Iter = llvm::find_if( - Mapping, [&](const std::pair &NameAndEnum) { - return NameAndEnum.first == Value; - }); - assert(Iter != Mapping.end() && "Unknown Case Value"); - store(Options, LocalName, Iter->second); - } - - private: - using NameAndValue = std::pair; - - std::optional getEnumInt(StringRef LocalName, - ArrayRef Mapping, - bool CheckGlobal, bool IgnoreCase) const; - - template - std::enable_if_t, std::vector> - typeEraseMapping() const { - ArrayRef> Mapping = - OptionEnumMapping::getEnumMapping(); - std::vector Result; - Result.reserve(Mapping.size()); - for (auto &MappedItem : Mapping) { - Result.emplace_back(static_cast(MappedItem.first), - MappedItem.second); - } - return Result; - } - - void storeInt(ClangTidyOptions::OptionMap &Options, StringRef LocalName, - int64_t Value) const; - - - std::string NamePrefix; - const ClangTidyOptions::OptionMap &CheckOptions; - ClangTidyContext *Context; - }; - -private: - void run(const ast_matchers::MatchFinder::MatchResult &Result) override; - std::string CheckName; - ClangTidyContext *Context; - -protected: - OptionsView Options; - /// Returns the main file name of the current translation unit. - StringRef getCurrentMainFile() const { return Context->getCurrentFile(); } - /// Returns the language options from the context. - const LangOptions &getLangOpts() const { return Context->getLangOpts(); } - /// Returns true when the check is run in a use case when only 1 fix will be - /// applied at a time. - bool areDiagsSelfContained() const { - return Context->areDiagsSelfContained(); - } - StringRef getID() const override { return CheckName; } -}; - -/// Read a named option from the ``Context`` and parse it as a bool. -/// -/// Reads the option with the check-local name \p LocalName from the -/// ``CheckOptions``. If the corresponding key is not present, return -/// ``std::nullopt``. -/// -/// If the corresponding key can't be parsed as a bool, emit a -/// diagnostic and return ``std::nullopt``. -template <> -std::optional -ClangTidyCheck::OptionsView::get(StringRef LocalName) const; - -/// Read a named option from the ``Context`` and parse it as a bool. -/// -/// Reads the option with the check-local name \p LocalName from the -/// ``CheckOptions``. If the corresponding key is not present, return -/// \p Default. -/// -/// If the corresponding key can't be parsed as a bool, emit a -/// diagnostic and return \p Default. -template <> -std::optional -ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName) const; - -/// Stores an option with the check-local name \p LocalName with -/// bool value \p Value to \p Options. -template <> -void ClangTidyCheck::OptionsView::store( - ClangTidyOptions::OptionMap &Options, StringRef LocalName, - bool Value) const; - - -} // namespace tidy -} // namespace clang - -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYCHECK_H diff --git a/ClangTidyDiagnosticConsumer.h b/ClangTidyDiagnosticConsumer.h deleted file mode 100644 index 9280eb1..0000000 --- a/ClangTidyDiagnosticConsumer.h +++ /dev/null @@ -1,324 +0,0 @@ -//===--- ClangTidyDiagnosticConsumer.h - clang-tidy -------------*- C++ -*-===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYDIAGNOSTICCONSUMER_H -#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYDIAGNOSTICCONSUMER_H - -#include "ClangTidyOptions.h" -#include "ClangTidyProfiling.h" -#include "FileExtensionsSet.h" -#include "NoLintDirectiveHandler.h" -#include "clang/Basic/Diagnostic.h" -#include "clang/Tooling/Core/Diagnostic.h" -#include "llvm/ADT/DenseMap.h" -#include "llvm/ADT/StringSet.h" -#include "llvm/Support/Regex.h" -#include - -namespace clang { - -class ASTContext; -class SourceManager; - -namespace tidy { -class CachedGlobList; - -/// A detected error complete with information to display diagnostic and -/// automatic fix. -/// -/// This is used as an intermediate format to transport Diagnostics without a -/// dependency on a SourceManager. -/// -/// FIXME: Make Diagnostics flexible enough to support this directly. -struct ClangTidyError : tooling::Diagnostic { - ClangTidyError(StringRef CheckName, Level DiagLevel, StringRef BuildDirectory, - bool IsWarningAsError); - - bool IsWarningAsError; - std::vector EnabledDiagnosticAliases; -}; - -/// Contains displayed and ignored diagnostic counters for a ClangTidy run. -struct ClangTidyStats { - unsigned ErrorsDisplayed = 0; - unsigned ErrorsIgnoredCheckFilter = 0; - unsigned ErrorsIgnoredNOLINT = 0; - unsigned ErrorsIgnoredNonUserCode = 0; - unsigned ErrorsIgnoredLineFilter = 0; - - unsigned errorsIgnored() const { - return ErrorsIgnoredNOLINT + ErrorsIgnoredCheckFilter + - ErrorsIgnoredNonUserCode + ErrorsIgnoredLineFilter; - } -}; - -/// 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: - /// Initializes \c ClangTidyContext instance. - ClangTidyContext(std::unique_ptr OptionsProvider, - bool AllowEnablingAnalyzerAlphaCheckers = false, - bool EnableModuleHeadersParsing = false); - /// Sets the DiagnosticsEngine that diag() will emit diagnostics to. - // FIXME: this is required initialization, and should be a constructor param. - // Fix the context -> diag engine -> consumer -> context initialization cycle. - void setDiagnosticsEngine(DiagnosticsEngine *DiagEngine) { - this->DiagEngine = DiagEngine; - } - - ~ClangTidyContext(); - - /// 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 Description, - DiagnosticIDs::Level Level = DiagnosticIDs::Warning); - - DiagnosticBuilder diag(StringRef CheckName, StringRef Description, - DiagnosticIDs::Level Level = DiagnosticIDs::Warning); - - DiagnosticBuilder diag(const tooling::Diagnostic &Error); - - /// Report any errors to do with reading the configuration using this method. - DiagnosticBuilder - configurationDiag(StringRef Message, - DiagnosticIDs::Level Level = DiagnosticIDs::Warning); - - /// Check whether a given diagnostic should be suppressed due to the presence - /// of a "NOLINT" suppression comment. - /// This is exposed so that other tools that present clang-tidy diagnostics - /// (such as clangd) can respect the same suppression rules as clang-tidy. - /// This does not handle suppression of notes following a suppressed - /// diagnostic; that is left to the caller as it requires maintaining state in - /// between calls to this function. - /// If any NOLINT is malformed, e.g. a BEGIN without a subsequent END, output - /// \param NoLintErrors will return an error about it. - /// If \param AllowIO is false, the function does not attempt to read source - /// files from disk which are not already mapped into memory; such files are - /// treated as not containing a suppression comment. - /// \param EnableNoLintBlocks controls whether to honor NOLINTBEGIN/NOLINTEND - /// blocks; if false, only considers line-level disabling. - bool - shouldSuppressDiagnostic(DiagnosticsEngine::Level DiagLevel, - const Diagnostic &Info, - SmallVectorImpl &NoLintErrors, - bool AllowIO = true, bool EnableNoLintBlocks = true); - - /// Sets the \c SourceManager of the used \c DiagnosticsEngine. - /// - /// This is called from the \c ClangTidyCheck base class. - void setSourceManager(SourceManager *SourceMgr); - - /// Should be called when starting to process new translation unit. - void setCurrentFile(StringRef File); - - /// Returns the main file name of the current translation unit. - StringRef getCurrentFile() const { return CurrentFile; } - - /// Sets ASTContext for the current translation unit. - void setASTContext(ASTContext *Context); - - /// Gets the language options from the AST context. - const LangOptions &getLangOpts() const { return LangOpts; } - - /// Returns the name of the clang-tidy check which produced this - /// diagnostic ID. - std::string getCheckName(unsigned DiagnosticID) const; - - /// Returns \c true if the check is enabled for the \c CurrentFile. - /// - /// The \c CurrentFile can be changed using \c setCurrentFile. - bool isCheckEnabled(StringRef CheckName) const; - - /// Returns \c true if the check should be upgraded to error for the - /// \c CurrentFile. - bool treatAsError(StringRef CheckName) const; - - /// Returns global options. - const ClangTidyGlobalOptions &getGlobalOptions() const; - - /// Returns options for \c CurrentFile. - /// - /// The \c CurrentFile can be changed using \c setCurrentFile. - const ClangTidyOptions &getOptions() const; - - /// Returns options for \c File. Does not change or depend on - /// \c CurrentFile. - ClangTidyOptions getOptionsForFile(StringRef File) const; - - const FileExtensionsSet &getHeaderFileExtensions() const { - return HeaderFileExtensions; - } - - const FileExtensionsSet &getImplementationFileExtensions() const { - return ImplementationFileExtensions; - } - - /// Returns \c ClangTidyStats containing issued and ignored diagnostic - /// counters. - const ClangTidyStats &getStats() const { return Stats; } - - /// Control profile collection in clang-tidy. - void setEnableProfiling(bool Profile); - bool getEnableProfiling() const { return Profile; } - - /// Control storage of profile date. - void setProfileStoragePrefix(StringRef ProfilePrefix); - std::optional - getProfileStorageParams() const; - - /// Should be called when starting to process new translation unit. - void setCurrentBuildDirectory(StringRef BuildDirectory) { - CurrentBuildDirectory = std::string(BuildDirectory); - } - - /// Returns build directory of the current translation unit. - const std::string &getCurrentBuildDirectory() const { - return CurrentBuildDirectory; - } - - /// If the experimental alpha checkers from the static analyzer can be - /// enabled. - bool canEnableAnalyzerAlphaCheckers() const { - return AllowEnablingAnalyzerAlphaCheckers; - } - - // This method determines whether preprocessor-level module header parsing is - // enabled using the `--experimental-enable-module-headers-parsing` option. - bool canEnableModuleHeadersParsing() const { - return EnableModuleHeadersParsing; - } - - void setSelfContainedDiags(bool Value) { SelfContainedDiags = Value; } - - bool areDiagsSelfContained() const { return SelfContainedDiags; } - - using DiagLevelAndFormatString = std::pair; - DiagLevelAndFormatString getDiagLevelAndFormatString(unsigned DiagnosticID, - SourceLocation Loc) { - return { - static_cast( - DiagEngine->getDiagnosticLevel(DiagnosticID, Loc)), - std::string( - DiagEngine->getDiagnosticIDs()->getDescription(DiagnosticID))}; - } - - void setOptionsCollector(llvm::StringSet<> *Collector) { - OptionsCollector = Collector; - } - llvm::StringSet<> *getOptionsCollector() const { return OptionsCollector; } - -private: - // Writes to Stats. - friend class ClangTidyDiagnosticConsumer; - - DiagnosticsEngine *DiagEngine = nullptr; - std::unique_ptr OptionsProvider; - - std::string CurrentFile; - ClangTidyOptions CurrentOptions; - - std::unique_ptr CheckFilter; - std::unique_ptr WarningAsErrorFilter; - - FileExtensionsSet HeaderFileExtensions; - FileExtensionsSet ImplementationFileExtensions; - - LangOptions LangOpts; - - ClangTidyStats Stats; - - std::string CurrentBuildDirectory; - - llvm::DenseMap CheckNamesByDiagnosticID; - - bool Profile = false; - std::string ProfilePrefix; - - bool AllowEnablingAnalyzerAlphaCheckers; - bool EnableModuleHeadersParsing; - - bool SelfContainedDiags = false; - - NoLintDirectiveHandler NoLintHandler; - llvm::StringSet<> *OptionsCollector = nullptr; -}; - -/// Gets the Fix attached to \p Diagnostic. -/// If there isn't a Fix attached to the diagnostic and \p AnyFix is true, Check -/// to see if exactly one note has a Fix and return it. Otherwise return -/// nullptr. -const llvm::StringMap * -getFixIt(const tooling::Diagnostic &Diagnostic, bool AnyFix); - -/// 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: - /// \param EnableNolintBlocks Enables diagnostic-disabling inside blocks of - /// code, delimited by NOLINTBEGIN and NOLINTEND. - ClangTidyDiagnosticConsumer(ClangTidyContext &Ctx, - DiagnosticsEngine *ExternalDiagEngine = nullptr, - bool RemoveIncompatibleErrors = true, - bool GetFixesFromNotes = false, - bool EnableNolintBlocks = true); - - // FIXME: The concept of converting between FixItHints and Replacements is - // more generic and should be pulled out into a more useful Diagnostics - // library. - void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, - const Diagnostic &Info) override; - - // Retrieve the diagnostics that were captured. - std::vector take(); - -private: - void finalizeLastError(); - void removeIncompatibleErrors(); - void removeDuplicatedDiagnosticsOfAliasCheckers(); - - /// Returns the \c HeaderFilter constructed for the options set in the - /// context. - llvm::Regex *getHeaderFilter(); - - /// Updates \c LastErrorRelatesToUserCode and LastErrorPassesLineFilter - /// according to the diagnostic \p Location. - void checkFilters(SourceLocation Location, const SourceManager &Sources); - bool passesLineFilter(StringRef FileName, unsigned LineNumber) const; - - void forwardDiagnostic(const Diagnostic &Info); - - ClangTidyContext &Context; - DiagnosticsEngine *ExternalDiagEngine; - bool RemoveIncompatibleErrors; - bool GetFixesFromNotes; - bool EnableNolintBlocks; - std::vector Errors; - std::unique_ptr HeaderFilter; - bool LastErrorRelatesToUserCode = false; - bool LastErrorPassesLineFilter = false; - bool LastErrorWasIgnored = false; -}; - -} // end namespace tidy -} // end namespace clang - -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYDIAGNOSTICCONSUMER_H diff --git a/ClangTidyForceLinker.h b/ClangTidyForceLinker.h deleted file mode 100644 index adde913..0000000 --- a/ClangTidyForceLinker.h +++ /dev/null @@ -1,142 +0,0 @@ -//===- ClangTidyForceLinker.h - clang-tidy --------------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYFORCELINKER_H -#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYFORCELINKER_H - -#include "clang-tidy-config.h" -#include "llvm/Support/Compiler.h" - -namespace clang::tidy { - -// This anchor is used to force the linker to link the AbseilModule. -extern volatile int AbseilModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED AbseilModuleAnchorDestination = - AbseilModuleAnchorSource; - -// This anchor is used to force the linker to link the AlteraModule. -extern volatile int AlteraModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED AlteraModuleAnchorDestination = - AlteraModuleAnchorSource; - -// This anchor is used to force the linker to link the AndroidModule. -extern volatile int AndroidModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED AndroidModuleAnchorDestination = - AndroidModuleAnchorSource; - -// This anchor is used to force the linker to link the BoostModule. -extern volatile int BoostModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED BoostModuleAnchorDestination = - BoostModuleAnchorSource; - -// This anchor is used to force the linker to link the BugproneModule. -extern volatile int BugproneModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED BugproneModuleAnchorDestination = - BugproneModuleAnchorSource; - -// This anchor is used to force the linker to link the CERTModule. -extern volatile int CERTModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED CERTModuleAnchorDestination = - CERTModuleAnchorSource; - -// This anchor is used to force the linker to link the ConcurrencyModule. -extern volatile int ConcurrencyModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED ConcurrencyModuleAnchorDestination = - ConcurrencyModuleAnchorSource; - -// 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 DarwinModule. -extern volatile int DarwinModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED DarwinModuleAnchorDestination = - DarwinModuleAnchorSource; - -// This anchor is used to force the linker to link the FuchsiaModule. -extern volatile int FuchsiaModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED FuchsiaModuleAnchorDestination = - FuchsiaModuleAnchorSource; - -// This anchor is used to force the linker to link the GoogleModule. -extern volatile int GoogleModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED GoogleModuleAnchorDestination = - GoogleModuleAnchorSource; - -// This anchor is used to force the linker to link the HICPPModule. -extern volatile int HICPPModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED HICPPModuleAnchorDestination = - HICPPModuleAnchorSource; - -// This anchor is used to force the linker to link the LinuxKernelModule. -extern volatile int LinuxKernelModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED LinuxKernelModuleAnchorDestination = - LinuxKernelModuleAnchorSource; - -// 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 LLVMLibcModule. -extern volatile int LLVMLibcModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED LLVMLibcModuleAnchorDestination = - LLVMLibcModuleAnchorSource; - -// 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; - -#if CLANG_TIDY_ENABLE_STATIC_ANALYZER && \ - !defined(CLANG_TIDY_DISABLE_STATIC_ANALYZER_CHECKS) -// This anchor is used to force the linker to link the MPIModule. -extern volatile int MPIModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED MPIModuleAnchorDestination = - MPIModuleAnchorSource; -#endif - -// This anchor is used to force the linker to link the ObjCModule. -extern volatile int ObjCModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED ObjCModuleAnchorDestination = - ObjCModuleAnchorSource; - -// This anchor is used to force the linker to link the OpenMPModule. -extern volatile int OpenMPModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED OpenMPModuleAnchorDestination = - OpenMPModuleAnchorSource; - -// This anchor is used to force the linker to link the PerformanceModule. -extern volatile int PerformanceModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED PerformanceModuleAnchorDestination = - PerformanceModuleAnchorSource; - -// This anchor is used to force the linker to link the PortabilityModule. -extern volatile int PortabilityModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED PortabilityModuleAnchorDestination = - PortabilityModuleAnchorSource; - -// This anchor is used to force the linker to link the ReadabilityModule. -extern volatile int ReadabilityModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED ReadabilityModuleAnchorDestination = - ReadabilityModuleAnchorSource; - -// This anchor is used to force the linker to link the ZirconModule. -extern volatile int ZirconModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED ZirconModuleAnchorDestination = - ZirconModuleAnchorSource; - -} // namespace clang::tidy - -#endif diff --git a/ClangTidyModule.h b/ClangTidyModule.h deleted file mode 100644 index 28f5433..0000000 --- a/ClangTidyModule.h +++ /dev/null @@ -1,98 +0,0 @@ -//===--- ClangTidyModule.h - clang-tidy -------------------------*- C++ -*-===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYMODULE_H -#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYMODULE_H - -#include "ClangTidyOptions.h" -#include "llvm/ADT/StringMap.h" -#include "llvm/ADT/StringRef.h" -#include -#include - -namespace clang::tidy { - -class ClangTidyCheck; -class ClangTidyContext; - -/// A collection of \c ClangTidyCheckFactory instances. -/// -/// All clang-tidy modules register their check factories with an instance of -/// this object. -class ClangTidyCheckFactories { -public: - using CheckFactory = std::function( - llvm::StringRef Name, ClangTidyContext *Context)>; - - /// Registers check \p Factory with name \p Name. - /// - /// For all checks that have default constructors, use \c registerCheck. - void registerCheckFactory(llvm::StringRef Name, CheckFactory Factory); - - /// 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(llvm::StringRef CheckName) { - registerCheckFactory(CheckName, - [](llvm::StringRef Name, ClangTidyContext *Context) { - return std::make_unique(Name, Context); - }); - } - - /// Create instances of checks that are enabled. - std::vector> - createChecks(ClangTidyContext *Context) const; - - /// Create instances of checks that are enabled for the current Language. - std::vector> - createChecksForLanguage(ClangTidyContext *Context) const; - - using FactoryMap = llvm::StringMap; - 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; -}; - -/// A clang-tidy module groups a number of \c ClangTidyChecks and gives -/// them a prefixed name. -class ClangTidyModule { -public: - virtual ~ClangTidyModule() {} - - /// Implement this function in order to register all \c CheckFactories - /// belonging to this module. - virtual void addCheckFactories(ClangTidyCheckFactories &CheckFactories) = 0; - - /// Gets default options for checks defined in this module. - virtual ClangTidyOptions getModuleOptions(); -}; - -} // namespace clang::tidy - -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYMODULE_H diff --git a/ClangTidyModuleRegistry.h b/ClangTidyModuleRegistry.h deleted file mode 100644 index 78d914b..0000000 --- a/ClangTidyModuleRegistry.h +++ /dev/null @@ -1,21 +0,0 @@ -//===--- ClangTidyModuleRegistry.h - clang-tidy -----------------*- C++ -*-===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYMODULEREGISTRY_H -#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYMODULEREGISTRY_H - -#include "ClangTidyModule.h" -#include "llvm/Support/Registry.h" - -namespace clang::tidy { - -using ClangTidyModuleRegistry = llvm::Registry; - -} // namespace clang::tidy - -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYMODULEREGISTRY_H diff --git a/ClangTidyOptions.h b/ClangTidyOptions.h deleted file mode 100644 index e7636cb..0000000 --- a/ClangTidyOptions.h +++ /dev/null @@ -1,329 +0,0 @@ -//===--- ClangTidyOptions.h - clang-tidy ------------------------*- C++ -*-===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYOPTIONS_H -#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYOPTIONS_H - -#include "llvm/ADT/IntrusiveRefCntPtr.h" -#include "llvm/ADT/StringMap.h" -#include "llvm/ADT/StringRef.h" -#include "llvm/Support/ErrorOr.h" -#include "llvm/Support/MemoryBufferRef.h" -#include "llvm/Support/VirtualFileSystem.h" -#include -#include -#include -#include -#include -#include - -namespace clang::tidy { - -/// Contains a list of line ranges in a single file. -struct FileFilter { - /// File name. - std::string Name; - - /// LineRange is a pair (inclusive). - using LineRange = std::pair; - - /// A list of line ranges in this file, for which we show warnings. - std::vector LineRanges; -}; - -/// Global options. These options are neither stored nor read from -/// configuration files. -struct ClangTidyGlobalOptions { - /// Output warnings from certain line ranges of certain files only. - /// If empty, no warnings will be filtered. - std::vector LineFilter; -}; - -/// Contains options for clang-tidy. These options may be read from -/// configuration files, and may be different for different translation units. -struct ClangTidyOptions { - /// 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(); - - /// Overwrites all fields in here by the fields of \p Other that have a value. - /// \p Order specifies precedence of \p Other option. - ClangTidyOptions &mergeWith(const ClangTidyOptions &Other, unsigned Order); - - /// Creates a new \c ClangTidyOptions instance combined from all fields - /// of this instance overridden by the fields of \p Other that have a value. - /// \p Order specifies precedence of \p Other option. - [[nodiscard]] ClangTidyOptions merge(const ClangTidyOptions &Other, - unsigned Order) const; - - /// Checks filter. - std::optional Checks; - - /// WarningsAsErrors filter. - std::optional WarningsAsErrors; - - /// File extensions to consider to determine if a given diagnostic is located - /// in a header file. - std::optional> HeaderFileExtensions; - - /// File extensions to consider to determine if a given diagnostic is located - /// is located in an implementation file. - std::optional> ImplementationFileExtensions; - - /// Output warnings from headers matching this filter. Warnings from - /// main files will always be displayed. - std::optional HeaderFilterRegex; - - /// Output warnings from system headers matching \c HeaderFilterRegex. - std::optional SystemHeaders; - - /// Format code around applied fixes with clang-format using this - /// style. - /// - /// Can be one of: - /// * 'none' - don't format code around applied fixes; - /// * 'llvm', 'google', 'mozilla' or other predefined clang-format style - /// names; - /// * 'file' - use the .clang-format file in the closest parent directory of - /// each source file; - /// * '{inline-formatting-style-in-yaml-format}'. - /// - /// See clang-format documentation for more about configuring format style. - std::optional FormatStyle; - - /// 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. - std::optional User; - - /// Helper structure for storing option value with priority of the value. - struct ClangTidyValue { - ClangTidyValue() = default; - ClangTidyValue(const char *Value) : Value(Value) {} - ClangTidyValue(llvm::StringRef Value, unsigned Priority = 0) - : Value(Value), Priority(Priority) {} - - std::string Value; - /// Priority stores relative precedence of the value loaded from config - /// files to disambiguate local vs global value from different levels. - unsigned Priority = 0; - }; - using StringPair = std::pair; - using OptionMap = llvm::StringMap; - - /// Key-value mapping used to store check-specific options. - OptionMap CheckOptions; - - using ArgList = std::vector; - - /// Add extra compilation arguments to the end of the list. - std::optional ExtraArgs; - - /// Add extra compilation arguments to the start of the list. - std::optional ExtraArgsBefore; - - /// Only used in the FileOptionsProvider and ConfigOptionsProvider. If true - /// and using a FileOptionsProvider, it will take a configuration file in the - /// parent directory (if any exists) and apply this config file on top of the - /// parent one. IF true and using a ConfigOptionsProvider, it will apply this - /// config on top of any configuration file it finds in the directory using - /// the same logic as FileOptionsProvider. If false or missing, only this - /// configuration file will be used. - std::optional InheritParentConfig; - - /// Use colors in diagnostics. If missing, it will be auto detected. - std::optional UseColor; -}; - -/// Abstract interface for retrieving various ClangTidy options. -class ClangTidyOptionsProvider { -public: - static const char OptionsSourceTypeDefaultBinary[]; - static const char OptionsSourceTypeCheckCommandLineOption[]; - static const char OptionsSourceTypeConfigCommandLineOption[]; - - virtual ~ClangTidyOptionsProvider() {} - - /// Returns global options, which are independent of the file. - virtual const ClangTidyGlobalOptions &getGlobalOptions() = 0; - - /// 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. - using OptionsSource = std::pair; - - /// Returns an ordered vector of OptionsSources, in order of increasing - /// priority. - virtual std::vector - getRawOptions(llvm::StringRef FileName) = 0; - - /// Returns options applying to a specific translation unit with the - /// specified \p FileName. - ClangTidyOptions getOptions(llvm::StringRef FileName); -}; - -/// Implementation of the \c ClangTidyOptionsProvider interface, which -/// returns the same options for all files. -class DefaultOptionsProvider : public ClangTidyOptionsProvider { -public: - DefaultOptionsProvider(ClangTidyGlobalOptions GlobalOptions, - ClangTidyOptions Options) - : GlobalOptions(std::move(GlobalOptions)), - DefaultOptions(std::move(Options)) {} - const ClangTidyGlobalOptions &getGlobalOptions() override { - return GlobalOptions; - } - std::vector getRawOptions(llvm::StringRef FileName) override; - -private: - ClangTidyGlobalOptions GlobalOptions; - ClangTidyOptions DefaultOptions; -}; - -class FileOptionsBaseProvider : public DefaultOptionsProvider { -protected: - // A pair of configuration file base name and a function parsing - // configuration from text in the corresponding format. - using ConfigFileHandler = std::pair (llvm::MemoryBufferRef)>>; - - /// 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 std::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. - using ConfigFileHandlers = std::vector; - - FileOptionsBaseProvider(ClangTidyGlobalOptions GlobalOptions, - ClangTidyOptions DefaultOptions, - ClangTidyOptions OverrideOptions, - llvm::IntrusiveRefCntPtr FS); - - FileOptionsBaseProvider(ClangTidyGlobalOptions GlobalOptions, - ClangTidyOptions DefaultOptions, - ClangTidyOptions OverrideOptions, - ConfigFileHandlers ConfigHandlers); - - void addRawFileOptions(llvm::StringRef AbsolutePath, - std::vector &CurOptions); - - /// Try to read configuration files from \p Directory using registered - /// \c ConfigHandlers. - std::optional tryReadConfigFile(llvm::StringRef Directory); - - llvm::StringMap CachedOptions; - ClangTidyOptions OverrideOptions; - ConfigFileHandlers ConfigHandlers; - llvm::IntrusiveRefCntPtr FS; -}; - -/// Implementation of ClangTidyOptions interface, which is used for -/// '-config' command-line option. -class ConfigOptionsProvider : public FileOptionsBaseProvider { -public: - ConfigOptionsProvider( - ClangTidyGlobalOptions GlobalOptions, ClangTidyOptions DefaultOptions, - ClangTidyOptions ConfigOptions, ClangTidyOptions OverrideOptions, - llvm::IntrusiveRefCntPtr FS = nullptr); - std::vector getRawOptions(llvm::StringRef FileName) override; - -private: - ClangTidyOptions ConfigOptions; -}; - -/// 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 FileOptionsBaseProvider { -public: - /// 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( - ClangTidyGlobalOptions GlobalOptions, ClangTidyOptions DefaultOptions, - ClangTidyOptions OverrideOptions, - llvm::IntrusiveRefCntPtr FS = nullptr); - - /// 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(ClangTidyGlobalOptions GlobalOptions, - ClangTidyOptions DefaultOptions, - ClangTidyOptions OverrideOptions, - ConfigFileHandlers ConfigHandlers); - - std::vector getRawOptions(llvm::StringRef FileName) override; -}; - -/// Parses LineFilter from JSON and stores it to the \p Options. -std::error_code parseLineFilter(llvm::StringRef LineFilter, - ClangTidyGlobalOptions &Options); - -/// Parses configuration from JSON and returns \c ClangTidyOptions or an -/// error. -llvm::ErrorOr -parseConfiguration(llvm::MemoryBufferRef Config); - -using DiagCallback = llvm::function_ref; - -llvm::ErrorOr -parseConfigurationWithDiags(llvm::MemoryBufferRef Config, DiagCallback Handler); - -/// Serializes configuration to a YAML-encoded string. -std::string configurationAsText(const ClangTidyOptions &Options); - -} // namespace clang::tidy - -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYOPTIONS_H diff --git a/ClangTidyProfiling.h b/ClangTidyProfiling.h deleted file mode 100644 index b6f7d66..0000000 --- a/ClangTidyProfiling.h +++ /dev/null @@ -1,58 +0,0 @@ -//===--- ClangTidyProfiling.h - clang-tidy ----------------------*- C++ -*-===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYPROFILING_H -#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYPROFILING_H - -#include "llvm/ADT/StringMap.h" -#include "llvm/Support/Chrono.h" -#include "llvm/Support/Timer.h" -#include -#include - -namespace llvm { -class raw_ostream; -} // namespace llvm - -namespace clang::tidy { - -class ClangTidyProfiling { -public: - struct StorageParams { - llvm::sys::TimePoint<> Timestamp; - std::string SourceFilename; - std::string StoreFilename; - - StorageParams() = default; - - StorageParams(llvm::StringRef ProfilePrefix, llvm::StringRef SourceFile); - }; - -private: - std::optional TG; - - std::optional Storage; - - void printUserFriendlyTable(llvm::raw_ostream &OS); - void printAsJSON(llvm::raw_ostream &OS); - - void storeProfileData(); - -public: - llvm::StringMap Records; - - ClangTidyProfiling() = default; - - ClangTidyProfiling(std::optional Storage); - - ~ClangTidyProfiling(); -}; - -} // namespace clang::tidy - -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYPROFILING_H diff --git a/aliceO2/AliceO2TidyModule.cpp b/aliceO2/AliceO2TidyModule.cpp index a8d79da..71f5ac1 100644 --- a/aliceO2/AliceO2TidyModule.cpp +++ b/aliceO2/AliceO2TidyModule.cpp @@ -7,9 +7,9 @@ // //===----------------------------------------------------------------------===// -#include "../ClangTidy.h" -#include "../ClangTidyModule.h" -#include "../ClangTidyModuleRegistry.h" +#include "clang-tidy/ClangTidy.h" +#include "clang-tidy/ClangTidyModule.h" +#include "clang-tidy/ClangTidyModuleRegistry.h" #include "MemberNamesCheck.h" #include "NamespaceNamingCheck.h" #include "SizeofCheck.h" diff --git a/aliceO2/MemberNamesCheck.h b/aliceO2/MemberNamesCheck.h index f61119e..1785110 100644 --- a/aliceO2/MemberNamesCheck.h +++ b/aliceO2/MemberNamesCheck.h @@ -10,8 +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 "../ClangTidyCheck.h" +#include "clang-tidy/ClangTidy.h" +#include "clang-tidy/ClangTidyCheck.h" #include namespace clang { diff --git a/aliceO2/NamespaceNamingCheck.h b/aliceO2/NamespaceNamingCheck.h index 17cc9e9..b5c08fc 100644 --- a/aliceO2/NamespaceNamingCheck.h +++ b/aliceO2/NamespaceNamingCheck.h @@ -10,8 +10,8 @@ #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ALICEO2_NAMESPACE_NAMING_H #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ALICEO2_NAMESPACE_NAMING_H -#include "../ClangTidy.h" -#include "../ClangTidyCheck.h" +#include "clang-tidy/ClangTidy.h" +#include "clang-tidy/ClangTidyCheck.h" namespace clang { namespace tidy { diff --git a/aliceO2/SizeofCheck.h b/aliceO2/SizeofCheck.h index c291f5f..7a02883 100644 --- a/aliceO2/SizeofCheck.h +++ b/aliceO2/SizeofCheck.h @@ -10,8 +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 "../ClangTidyCheck.h" +#include "clang-tidy/ClangTidy.h" +#include "clang-tidy/ClangTidyCheck.h" namespace clang { namespace tidy { diff --git a/plugin/FooCheck.h b/plugin/FooCheck.h index 2039ccc..5d843bb 100644 --- a/plugin/FooCheck.h +++ b/plugin/FooCheck.h @@ -10,8 +10,8 @@ #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PLUGIN_FOO_H #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PLUGIN_FOO_H -#include "../ClangTidy.h" -#include "../ClangTidyCheck.h" +#include "clang-tidy/ClangTidy.h" +#include "clang-tidy/ClangTidyCheck.h" namespace clang { namespace tidy { diff --git a/plugin/PluginTidyModule.cpp b/plugin/PluginTidyModule.cpp index 20a726e..c8f4b10 100644 --- a/plugin/PluginTidyModule.cpp +++ b/plugin/PluginTidyModule.cpp @@ -7,9 +7,9 @@ // //===----------------------------------------------------------------------===// -#include "../ClangTidy.h" -#include "../ClangTidyModule.h" -#include "../ClangTidyModuleRegistry.h" +#include "clang-tidy/ClangTidy.h" +#include "clang-tidy/ClangTidyModule.h" +#include "clang-tidy/ClangTidyModuleRegistry.h" #include "FooCheck.h" #include diff --git a/reporting/InterfaceLister.h b/reporting/InterfaceLister.h index f517be6..5a4c91a 100644 --- a/reporting/InterfaceLister.h +++ b/reporting/InterfaceLister.h @@ -10,8 +10,8 @@ #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_INTERFACELISTER_NAMES_H #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_INTERFACELISTER_NAMES_H -#include "../ClangTidy.h" -#include "../ClangTidyCheck.h" +#include "clang-tidy/ClangTidy.h" +#include "clang-tidy/ClangTidyCheck.h" namespace clang { namespace tidy { diff --git a/reporting/ReportingTidyModule.cpp b/reporting/ReportingTidyModule.cpp index adf1f7d..3674a70 100644 --- a/reporting/ReportingTidyModule.cpp +++ b/reporting/ReportingTidyModule.cpp @@ -7,9 +7,9 @@ // //===----------------------------------------------------------------------===// -#include "../ClangTidy.h" -#include "../ClangTidyModule.h" -#include "../ClangTidyModuleRegistry.h" +#include "clang-tidy/ClangTidy.h" +#include "clang-tidy/ClangTidyModule.h" +#include "clang-tidy/ClangTidyModuleRegistry.h" #include "InterfaceLister.h" #include "VirtFuncLister.h" diff --git a/reporting/VirtFuncLister.h b/reporting/VirtFuncLister.h index 5f3a6b2..d8ccf21 100644 --- a/reporting/VirtFuncLister.h +++ b/reporting/VirtFuncLister.h @@ -10,8 +10,8 @@ #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_VIRTFUNCLISTER_NAMES_H #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_VIRTFUNCLISTER_NAMES_H -#include "../ClangTidy.h" -#include "../ClangTidyCheck.h" +#include "clang-tidy/ClangTidy.h" +#include "clang-tidy/ClangTidyCheck.h" namespace clang { namespace tidy { diff --git a/tool/ClangTidyMain.cpp b/tool/ClangTidyMain.cpp index 6e9618d..48066ef 100644 --- a/tool/ClangTidyMain.cpp +++ b/tool/ClangTidyMain.cpp @@ -15,8 +15,8 @@ //===----------------------------------------------------------------------===// #include "ClangTidyMain.h" -#include "../ClangTidy.h" -#include "../ClangTidyForceLinker.h" +#include "clang-tidy/ClangTidy.h" +//#include "clang-tidy/ClangTidyForceLinker.h" #include "../GlobList.h" #include "clang/Tooling/CommonOptionsParser.h" #include "llvm/ADT/StringSet.h" @@ -415,7 +415,7 @@ static bool verifyChecks(const StringSet<> &AllChecks, StringRef CheckGlob, if (Cur.empty()) continue; Cur.consume_front("-"); - if (Cur.startswith("clang-diagnostic")) + if (Cur.starts_with("clang-diagnostic")) continue; if (Cur.contains('*')) { SmallString<128> RegexText("^");