Skip to content

[clang-tidy] Add readability-redundant-casting check #70595

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions clang-tools-extra/clang-tidy/readability/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ add_clang_library(clangTidyReadabilityModule
QualifiedAutoCheck.cpp
ReadabilityTidyModule.cpp
RedundantAccessSpecifiersCheck.cpp
RedundantCastingCheck.cpp
RedundantControlFlowCheck.cpp
RedundantDeclarationCheck.cpp
RedundantFunctionPtrDereferenceCheck.cpp
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
#include "OperatorsRepresentationCheck.h"
#include "QualifiedAutoCheck.h"
#include "RedundantAccessSpecifiersCheck.h"
#include "RedundantCastingCheck.h"
#include "RedundantControlFlowCheck.h"
#include "RedundantDeclarationCheck.h"
#include "RedundantFunctionPtrDereferenceCheck.h"
Expand Down Expand Up @@ -117,6 +118,8 @@ class ReadabilityModule : public ClangTidyModule {
"readability-qualified-auto");
CheckFactories.registerCheck<RedundantAccessSpecifiersCheck>(
"readability-redundant-access-specifiers");
CheckFactories.registerCheck<RedundantCastingCheck>(
"readability-redundant-casting");
CheckFactories.registerCheck<RedundantFunctionPtrDereferenceCheck>(
"readability-redundant-function-ptr-dereference");
CheckFactories.registerCheck<RedundantMemberInitCheck>(
Expand Down
252 changes: 252 additions & 0 deletions clang-tools-extra/clang-tidy/readability/RedundantCastingCheck.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
//===--- RedundantCastingCheck.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 "RedundantCastingCheck.h"
#include "../utils/FixItHintUtils.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"

using namespace clang::ast_matchers;

namespace clang::tidy::readability {

static bool areTypesEqual(QualType S, QualType D) {
if (S == D)
return true;

const auto *TS = S->getAs<TypedefType>();
const auto *TD = D->getAs<TypedefType>();
if (TS != TD)
return false;

QualType PtrS = S->getPointeeType();
QualType PtrD = D->getPointeeType();

if (!PtrS.isNull() && !PtrD.isNull())
return areTypesEqual(PtrS, PtrD);

const DeducedType *DT = S->getContainedDeducedType();
if (DT && DT->isDeduced())
return D == DT->getDeducedType();

return false;
}

static bool areTypesEqual(QualType TypeS, QualType TypeD,
bool IgnoreTypeAliases) {
const QualType CTypeS = TypeS.getCanonicalType();
const QualType CTypeD = TypeD.getCanonicalType();
if (CTypeS != CTypeD)
return false;

return IgnoreTypeAliases || areTypesEqual(TypeS.getLocalUnqualifiedType(),
TypeD.getLocalUnqualifiedType());
}

static bool areBinaryOperatorOperandsTypesEqualToOperatorResultType(
const Expr *E, bool IgnoreTypeAliases) {
if (!E)
return true;
const Expr *WithoutImplicitAndParen = E->IgnoreParenImpCasts();
if (!WithoutImplicitAndParen)
return true;
if (const auto *B = dyn_cast<BinaryOperator>(WithoutImplicitAndParen)) {
const QualType Type = WithoutImplicitAndParen->getType();
if (Type.isNull())
return true;

const QualType NonReferenceType = Type.getNonReferenceType();
const QualType LHSType = B->getLHS()->IgnoreImplicit()->getType();
if (LHSType.isNull() || !areTypesEqual(LHSType.getNonReferenceType(),
NonReferenceType, IgnoreTypeAliases))
return false;
const QualType RHSType = B->getRHS()->IgnoreImplicit()->getType();
if (RHSType.isNull() || !areTypesEqual(RHSType.getNonReferenceType(),
NonReferenceType, IgnoreTypeAliases))
return false;
}
return true;
}

static const Decl *getSourceExprDecl(const Expr *SourceExpr) {
const Expr *CleanSourceExpr = SourceExpr->IgnoreParenImpCasts();
if (const auto *E = dyn_cast<DeclRefExpr>(CleanSourceExpr)) {
return E->getDecl();
}

if (const auto *E = dyn_cast<CallExpr>(CleanSourceExpr)) {
return E->getCalleeDecl();
}

if (const auto *E = dyn_cast<MemberExpr>(CleanSourceExpr)) {
return E->getMemberDecl();
}
return nullptr;
}

RedundantCastingCheck::RedundantCastingCheck(StringRef Name,
ClangTidyContext *Context)
: ClangTidyCheck(Name, Context),
IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", true)),
IgnoreTypeAliases(Options.getLocalOrGlobal("IgnoreTypeAliases", false)) {}

void RedundantCastingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
Options.store(Opts, "IgnoreMacros", IgnoreMacros);
Options.store(Opts, "IgnoreTypeAliases", IgnoreTypeAliases);
}

void RedundantCastingCheck::registerMatchers(MatchFinder *Finder) {
auto SimpleType = qualType(hasCanonicalType(
qualType(anyOf(builtinType(), references(builtinType()),
references(pointsTo(qualType())), pointsTo(qualType())))));

auto BitfieldMemberExpr = memberExpr(member(fieldDecl(isBitField())));

Finder->addMatcher(
explicitCastExpr(
unless(hasCastKind(CK_ConstructorConversion)),
unless(hasCastKind(CK_UserDefinedConversion)),
unless(cxxFunctionalCastExpr(hasDestinationType(unless(SimpleType)))),

hasDestinationType(qualType().bind("dstType")),
hasSourceExpression(anyOf(
expr(unless(initListExpr()), unless(BitfieldMemberExpr),
hasType(qualType().bind("srcType")))
.bind("source"),
initListExpr(unless(hasInit(1, expr())),
hasInit(0, expr(unless(BitfieldMemberExpr),
hasType(qualType().bind("srcType")))
.bind("source"))))))
.bind("cast"),
this);
}

void RedundantCastingCheck::check(const MatchFinder::MatchResult &Result) {
const auto *SourceExpr = Result.Nodes.getNodeAs<Expr>("source");
auto TypeD = *Result.Nodes.getNodeAs<QualType>("dstType");

if (SourceExpr->getValueKind() == VK_LValue &&
TypeD.getCanonicalType()->isRValueReferenceType())
return;

const auto TypeS =
Result.Nodes.getNodeAs<QualType>("srcType")->getNonReferenceType();
TypeD = TypeD.getNonReferenceType();

if (!areTypesEqual(TypeS, TypeD, IgnoreTypeAliases))
return;

if (!areBinaryOperatorOperandsTypesEqualToOperatorResultType(
SourceExpr, IgnoreTypeAliases))
return;

const auto *CastExpr = Result.Nodes.getNodeAs<ExplicitCastExpr>("cast");
if (IgnoreMacros &&
(CastExpr->getBeginLoc().isMacroID() ||
CastExpr->getEndLoc().isMacroID() || CastExpr->getExprLoc().isMacroID()))
return;

{
auto Diag = diag(CastExpr->getExprLoc(),
"redundant explicit casting to the same type %0 as the "
"sub-expression, remove this casting");
Diag << TypeD;

const SourceManager &SM = *Result.SourceManager;
const SourceLocation SourceExprBegin =
SM.getExpansionLoc(SourceExpr->getBeginLoc());
const SourceLocation SourceExprEnd =
SM.getExpansionLoc(SourceExpr->getEndLoc());

if (SourceExprBegin != CastExpr->getBeginLoc())
Diag << FixItHint::CreateRemoval(SourceRange(
CastExpr->getBeginLoc(), SourceExprBegin.getLocWithOffset(-1)));

const SourceLocation NextToken = Lexer::getLocForEndOfToken(
SourceExprEnd, 0U, SM, Result.Context->getLangOpts());

if (SourceExprEnd != CastExpr->getEndLoc()) {
Diag << FixItHint::CreateRemoval(
SourceRange(NextToken, CastExpr->getEndLoc()));
}

if (utils::fixit::areParensNeededForStatement(*SourceExpr)) {
Diag << FixItHint::CreateInsertion(SourceExprBegin, "(")
<< FixItHint::CreateInsertion(NextToken, ")");
}
}

const auto *SourceExprDecl = getSourceExprDecl(SourceExpr);
if (!SourceExprDecl)
return;

if (const auto *D = dyn_cast<CXXConstructorDecl>(SourceExprDecl)) {
diag(D->getLocation(),
"source type originates from the invocation of this constructor",
DiagnosticIDs::Note);
return;
}

if (const auto *D = dyn_cast<FunctionDecl>(SourceExprDecl)) {
diag(D->getLocation(),
"source type originates from the invocation of this "
"%select{function|method}0",
DiagnosticIDs::Note)
<< isa<CXXMethodDecl>(D) << D->getReturnTypeSourceRange();
return;
}

if (const auto *D = dyn_cast<FieldDecl>(SourceExprDecl)) {
diag(D->getLocation(),
"source type originates from referencing this member",
DiagnosticIDs::Note)
<< SourceRange(D->getTypeSpecStartLoc(), D->getTypeSpecEndLoc());
return;
}

if (const auto *D = dyn_cast<ParmVarDecl>(SourceExprDecl)) {
diag(D->getLocation(),
"source type originates from referencing this parameter",
DiagnosticIDs::Note)
<< SourceRange(D->getTypeSpecStartLoc(), D->getTypeSpecEndLoc());
return;
}

if (const auto *D = dyn_cast<VarDecl>(SourceExprDecl)) {
diag(D->getLocation(),
"source type originates from referencing this variable",
DiagnosticIDs::Note)
<< SourceRange(D->getTypeSpecStartLoc(), D->getTypeSpecEndLoc());
return;
}

if (const auto *D = dyn_cast<EnumConstantDecl>(SourceExprDecl)) {
diag(D->getLocation(),
"source type originates from referencing this enum constant",
DiagnosticIDs::Note);
return;
}

if (const auto *D = dyn_cast<BindingDecl>(SourceExprDecl)) {
diag(D->getLocation(),
"source type originates from referencing this bound variable",
DiagnosticIDs::Note);
return;
}

if (const auto *D = dyn_cast<NonTypeTemplateParmDecl>(SourceExprDecl)) {
diag(D->getLocation(),
"source type originates from referencing this non-type template "
"parameter",
DiagnosticIDs::Note);
return;
}
}

} // namespace clang::tidy::readability
38 changes: 38 additions & 0 deletions clang-tools-extra/clang-tidy/readability/RedundantCastingCheck.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
//===--- RedundantCastingCheck.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_READABILITY_REDUNDANTCASTINGCHECK_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_REDUNDANTCASTINGCHECK_H

#include "../ClangTidyCheck.h"

namespace clang::tidy::readability {

/// Detects explicit type casting operations that involve the same source and
/// destination types, and subsequently recommend their removal.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/readability/redundant-casting.html
class RedundantCastingCheck : public ClangTidyCheck {
public:
RedundantCastingCheck(StringRef Name, ClangTidyContext *Context);
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
std::optional<TraversalKind> getCheckTraversalKind() const override {
return TK_IgnoreUnlessSpelledInSource;
}

private:
const bool IgnoreMacros;
const bool IgnoreTypeAliases;
};

} // namespace clang::tidy::readability

#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_REDUNDANTCASTINGCHECK_H
1 change: 1 addition & 0 deletions clang-tools-extra/clang-tidy/utils/FixItHintUtils.h
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ std::string formatDereference(const Expr &ExprNode, const ASTContext &Context);
// \brief Checks whatever a expression require extra () to be always used in
// safe way in any other expression.
bool areParensNeededForStatement(const Stmt &Node);

} // namespace clang::tidy::utils::fixit

#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_UTILS_FIXITHINTUTILS_H
6 changes: 6 additions & 0 deletions clang-tools-extra/docs/ReleaseNotes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,12 @@ New checks
Finds return statements with ``void`` values used within functions with
``void`` result types.

- New :doc:`readability-redundant-casting
<clang-tidy/checks/readability/redundant-casting>` check.

Detects explicit type casting operations that involve the same source and
destination types, and subsequently recommend their removal.

- New :doc:`readability-reference-to-constructed-temporary
<clang-tidy/checks/readability/reference-to-constructed-temporary>` check.

Expand Down
1 change: 1 addition & 0 deletions clang-tools-extra/docs/clang-tidy/checks/list.rst
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,7 @@ Clang-Tidy Checks
:doc:`readability-operators-representation <readability/operators-representation>`, "Yes"
:doc:`readability-qualified-auto <readability/qualified-auto>`, "Yes"
:doc:`readability-redundant-access-specifiers <readability/redundant-access-specifiers>`, "Yes"
:doc:`readability-redundant-casting <readability/redundant-casting>`, "Yes"
:doc:`readability-redundant-control-flow <readability/redundant-control-flow>`, "Yes"
:doc:`readability-redundant-declaration <readability/redundant-declaration>`, "Yes"
:doc:`readability-redundant-function-ptr-dereference <readability/redundant-function-ptr-dereference>`, "Yes"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
.. title:: clang-tidy - readability-redundant-casting

readability-redundant-casting
=============================

Detects explicit type casting operations that involve the same source and
destination types, and subsequently recommend their removal. Covers a range of
explicit casting operations, including ``static_cast``, ``const_cast``, C-style
casts, and ``reinterpret_cast``. Its primary objective is to enhance code
readability and maintainability by eliminating unnecessary type casting.

.. code-block:: c++

int value = 42;
int result = static_cast<int>(value);

In this example, the ``static_cast<int>(value)`` is redundant, as it performs
a cast from an ``int`` to another ``int``.

Casting operations involving constructor conversions, user-defined conversions,
functional casts, type-dependent casts, casts between distinct type aliases that
refer to the same underlying type, as well as bitfield-related casts and casts
directly from lvalue to rvalue, are all disregarded by the check.

Options
-------

.. option:: IgnoreMacros

If set to `true`, the check will not give warnings inside macros. Default
is `true`.

.. option:: IgnoreTypeAliases

When set to `false`, the check will consider type aliases, and when set to
`true`, it will resolve all type aliases and operate on the underlying
types. Default is `false`.
Loading