[clang-tools-extra] [clang-tidy] Add `modernize-use-as-const` check (PR #210554)
Lucas Ly Ba via cfe-commits
cfe-commits at lists.llvm.org
Tue Jul 28 18:40:28 PDT 2026
================
@@ -0,0 +1,85 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 "UseAsConstCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+UseAsConstCheck::UseAsConstCheck(StringRef Name, ClangTidyContext *Context)
+ : ClangTidyCheck(Name, Context),
+ Inserter(Options.getLocalOrGlobal("IncludeStyle",
+ utils::IncludeSorter::IS_LLVM),
+ areDiagsSelfContained()) {}
+
+void UseAsConstCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
+ Options.store(Opts, "IncludeStyle", Inserter.getStyle());
+}
+
+void UseAsConstCheck::registerMatchers(MatchFinder *Finder) {
+ // Match a static_cast to a const-qualified type; check() narrows it down.
+ Finder->addMatcher(
+ cxxStaticCastExpr(hasType(qualType(isConstQualified()))).bind("cast"),
+ this);
+}
+
+void UseAsConstCheck::registerPPCallbacks(const SourceManager &SM,
+ Preprocessor *PP,
+ Preprocessor *ModuleExpanderPP) {
+ Inserter.registerPreprocessor(PP);
+}
+
+void UseAsConstCheck::check(const MatchFinder::MatchResult &Result) {
+ const auto *Cast = Result.Nodes.getNodeAs<CXXStaticCastExpr>("cast");
+ // A cast written in a macro cannot be safely rewritten.
+ if (Cast->getBeginLoc().isMacroID() || Cast->getEndLoc().isMacroID())
+ return;
+
+ // Only handle a cast written as 'const T &'.
+ const auto *RefType = Cast->getTypeAsWritten()->getAs<LValueReferenceType>();
+ if (!RefType)
+ return;
+ QualType Pointee = RefType->getPointeeType();
+ if (!Pointee.isConstQualified())
+ return;
----------------
lucasly-ba wrote:
the cast expression's own type is the pointee, so the & only shows up as written, will add some !
https://github.com/llvm/llvm-project/pull/210554
More information about the cfe-commits
mailing list