[clang-tools-extra] [clang-tidy] Add modernize-use-to-underlying check (PR #210459)
Yanzuo Liu via cfe-commits
cfe-commits at lists.llvm.org
Fri Jul 17 21:42:25 PDT 2026
================
@@ -0,0 +1,163 @@
+//===--- UseToUnderlyingCheck.cpp - 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
+//
+//===----------------------------------------------------------------------===//
+
+#include "UseToUnderlyingCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy {
+
+template <>
+struct OptionEnumMapping<modernize::UseToUnderlyingCheck::ImpreciseCastsKind> {
+ static llvm::ArrayRef<
+ std::pair<modernize::UseToUnderlyingCheck::ImpreciseCastsKind, StringRef>>
+ getEnumMapping() {
+ using ImpreciseCastsKind =
+ modernize::UseToUnderlyingCheck::ImpreciseCastsKind;
+ static constexpr std::pair<ImpreciseCastsKind, StringRef> Mapping[] = {
+ {ImpreciseCastsKind::Ignore, "Ignore"},
+ {ImpreciseCastsKind::Warn, "Warn"},
+ {ImpreciseCastsKind::PreserveType, "PreserveType"},
+ {ImpreciseCastsKind::UseUnderlyingType, "UseUnderlyingType"},
+ };
+ return {Mapping};
+ }
+};
+
+} // namespace clang::tidy
+
+namespace clang::tidy::modernize {
+
+UseToUnderlyingCheck::UseToUnderlyingCheck(StringRef Name,
+ ClangTidyContext *Context)
+ : ClangTidyCheck(Name, Context),
+ ImpreciseCasts(Options.get("ImpreciseCasts", ImpreciseCastsKind::Warn)),
+ ReplacementFunction(
+ Options.get("ReplacementFunction", "std::to_underlying")),
+ IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
+ utils::IncludeSorter::IS_LLVM),
+ areDiagsSelfContained()),
+ MaybeHeaderToInclude(Options.get("ReplacementFunctionHeader")) {
+ if (!MaybeHeaderToInclude && ReplacementFunction == "std::to_underlying")
----------------
zwuis wrote:
We can warn when the replacement function is `std::to_underlying` but the header is not `<utility>`.
https://github.com/llvm/llvm-project/pull/210459
More information about the cfe-commits
mailing list