-
Notifications
You must be signed in to change notification settings - Fork 15.1k
[clang-tidy] New check for static_cast of an enum class type #167144
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
Open
divvelarakesh1
wants to merge
1
commit into
llvm:main
Choose a base branch
from
divvelarakesh1:Fix_static_cast_of_enum_class
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+205
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
80 changes: 80 additions & 0 deletions
80
clang-tools-extra/clang-tidy/modernize/UseToUnderlyingCheck.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| //===----------------------------------------------------------------------===// | ||
| // | ||
| // 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/ASTMatchers/ASTMatchFinder.h" | ||
| #include "clang/AST/ASTContext.h" | ||
| #include "clang/ASTMatchers/ASTMatchers.h" | ||
| #include "clang/Lex/Lexer.h" | ||
| #include "clang/Lex/Preprocessor.h" | ||
| #include "llvm/Support/Error.h" // You'll want this for the inserter | ||
| using namespace clang::ast_matchers; | ||
|
|
||
| namespace clang::tidy::modernize { | ||
| //Constructor | ||
| UseToUnderlyingCheck::UseToUnderlyingCheck(StringRef Name, | ||
| ClangTidyContext *Context) | ||
| : ClangTidyCheck(Name, Context), | ||
| Inserter(Options.getLocalOrGlobal("IncludeStyle", | ||
| utils::IncludeSorter::IS_LLVM), | ||
| areDiagsSelfContained()) {} | ||
| // | ||
| void UseToUnderlyingCheck::registerPPCallbacks(const SourceManager &SM, | ||
| Preprocessor *PP, | ||
| Preprocessor *ModuleExpanderPP) { | ||
| Inserter.registerPreprocessor(PP); | ||
| } | ||
| // | ||
| void UseToUnderlyingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { | ||
| Options.store(Opts, "IncludeStyle", Inserter.getStyle()); | ||
| } | ||
| //Language version compatibility checking | ||
| bool UseToUnderlyingCheck::isLanguageVersionSupported(const LangOptions &LangOpts) const{ | ||
| return LangOpts.CPlusPlus23; | ||
| } | ||
|
|
||
| // | ||
| void UseToUnderlyingCheck::registerMatchers(MatchFinder *Finder) { | ||
| // FIXME: Add matchers. | ||
| Finder->addMatcher( | ||
| cxxStaticCastExpr( //C++ cast | ||
| hasDestinationType(isInteger()), //casting to any type of integer (int,long,etc) | ||
| hasSourceExpression( //is an enum class | ||
| expr(hasType(enumType(hasDeclaration(enumDecl(isScoped()))))) | ||
| .bind("enumExpr"))) //giving the name enumExpr | ||
| .bind("castExpr"), //giving the name castExpr | ||
| this); | ||
| } | ||
| \ | ||
| void UseToUnderlyingCheck::check(const MatchFinder::MatchResult &Result) { | ||
| //Acquiring the enumExpr and castExpr using getNodeAS | ||
| const auto *Enum = Result.Nodes.getNodeAs<Expr>("enumExpr"); | ||
| const auto *Cast = Result.Nodes.getNodeAs<CXXStaticCastExpr>("castExpr"); | ||
|
|
||
| //getting contents of that node using getsourcetext | ||
| StringRef EnumExprText = Lexer::getSourceText( | ||
| CharSourceRange::getTokenRange(Enum->getSourceRange()), | ||
| *Result.SourceManager, getLangOpts()); | ||
| //Suggestion to the user regarding the cast expr | ||
| std::string Replacement = ("std::to_underlying(" + EnumExprText + ")").str(); | ||
| // gives and watring message if static cast is used instead to_underlying | ||
| auto Diag=diag(Cast->getBeginLoc(), "use 'std::to_underlying' instead of 'static_cast' for 'enum class'"); | ||
| //suggest and hint for fixing it. | ||
| Diag<< FixItHint::CreateReplacement(Cast->getSourceRange(), Replacement); | ||
|
|
||
| Diag << Inserter.createIncludeInsertion( | ||
| Result.Context->getSourceManager().getFileID(Cast->getBeginLoc()), | ||
| "<utility>"); | ||
|
|
||
|
|
||
| // Required error handling for the Inserter | ||
|
|
||
| } | ||
|
|
||
|
|
||
| } // namespace clang::tidy::modernize | ||
36 changes: 36 additions & 0 deletions
36
clang-tools-extra/clang-tidy/modernize/UseToUnderlyingCheck.h
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| //===----------------------------------------------------------------------===// | ||
| // | ||
| // 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_MODERNIZE_USETOUNDERLYINGCHECK_H | ||
| #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_USETOUNDERLYINGCHECK_H | ||
|
|
||
| #include "../ClangTidyCheck.h" | ||
| #include "../utils/IncludeInserter.h" | ||
|
|
||
| namespace clang::tidy::modernize { | ||
|
|
||
| /// FIXME: Write a short description. | ||
| /// | ||
| /// For the user-facing documentation see: | ||
| /// https://clang.llvm.org/extra/clang-tidy/checks/modernize/use-to-underlying.html | ||
| class UseToUnderlyingCheck : public ClangTidyCheck { | ||
| public: | ||
| UseToUnderlyingCheck(StringRef Name, ClangTidyContext *Context); | ||
| void registerMatchers(ast_matchers::MatchFinder *Finder) override; | ||
| void check(const ast_matchers::MatchFinder::MatchResult &Result) override; | ||
| bool isLanguageVersionSupported(const LangOptions &LangOpts) const override; | ||
| void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, | ||
| Preprocessor *ModuleExpanderPP) override; | ||
| void storeOptions(ClangTidyOptions::OptionMap &Opts) override; | ||
| private: | ||
| utils::IncludeInserter Inserter; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please run Clang-Format. |
||
| }; | ||
|
|
||
| } // namespace clang::tidy::modernize | ||
|
|
||
| #endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_USETOUNDERLYINGCHECK_H | ||
89 changes: 89 additions & 0 deletions
89
clang-tools-extra/test/clang-tidy/checkers/modernize/use-to-underlying.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| // RUN: %check_clang_tidy -std=c++23 %s modernize-use-to-underlying %t | ||
|
|
||
| // Mock std::to_underlying for testing | ||
| namespace std { | ||
| template<typename T> | ||
| constexpr auto to_underlying(T value) noexcept { | ||
| return static_cast<__underlying_type(T)>(value); | ||
| } | ||
| } | ||
|
|
||
| // Test case 1: Basic enum class to int cast - should warn | ||
| enum class MyEnum { A = 1, B = 2 }; | ||
|
|
||
| void test_basic_cast() { | ||
| int value = static_cast<int>(MyEnum::A); | ||
| // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: use 'std::to_underlying' instead of 'static_cast' for 'enum class' [modernize-use-to-underlying] | ||
| // CHECK-FIXES: int value = std::to_underlying(MyEnum::A); | ||
| } | ||
|
|
||
| // Test case 2: enum class to long cast - should warn | ||
| void test_long_cast() { | ||
| long value = static_cast<long>(MyEnum::B); | ||
| // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: use 'std::to_underlying' instead of 'static_cast' for 'enum class' [modernize-use-to-underlying] | ||
| // CHECK-FIXES: long value = std::to_underlying(MyEnum::B); | ||
| } | ||
|
|
||
| // Test case 3: enum class in expression - should warn | ||
| void test_expression() { | ||
| int result = static_cast<int>(MyEnum::A) + 10; | ||
| // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: use 'std::to_underlying' instead of 'static_cast' for 'enum class' [modernize-use-to-underlying] | ||
| // CHECK-FIXES: int result = std::to_underlying(MyEnum::A) + 10; | ||
| } | ||
|
|
||
| // Test case 4: Already using std::to_underlying - should NOT warn | ||
| void test_already_correct() { | ||
| int value = std::to_underlying(MyEnum::B); | ||
| // No warning expected | ||
| } | ||
|
|
||
| // Test case 5: Casting float to int - should NOT warn (not an enum) | ||
| void test_float_cast() { | ||
| float y = 8.34; | ||
| int z = static_cast<int>(y); | ||
| // No warning expected | ||
| } | ||
|
|
||
| // Test case 6: Regular (non-scoped) enum - should NOT warn | ||
| enum RegularEnum { X = 1, Y = 2 }; | ||
|
|
||
| void test_regular_enum() { | ||
| int value = static_cast<int>(RegularEnum::X); | ||
| // No warning expected (only enum class should trigger) | ||
| } | ||
|
|
||
| // Test case 7: Multiple casts in same function - should warn for each | ||
| void test_multiple_casts() { | ||
| int a = static_cast<int>(MyEnum::A); | ||
| // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: use 'std::to_underlying' instead of 'static_cast' for 'enum class' [modernize-use-to-underlying] | ||
| // CHECK-FIXES: int a = std::to_underlying(MyEnum::A); | ||
|
|
||
| int b = static_cast<int>(MyEnum::B); | ||
| // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: use 'std::to_underlying' instead of 'static_cast' for 'enum class' [modernize-use-to-underlying] | ||
| // CHECK-FIXES: int b = std::to_underlying(MyEnum::B); | ||
| } | ||
|
|
||
| // Test case 8: enum class with underlying type specified | ||
| enum class TypedEnum : unsigned int { First = 0, Second = 1 }; | ||
|
|
||
| void test_typed_enum() { | ||
| unsigned int val = static_cast<unsigned int>(TypedEnum::First); | ||
| // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: use 'std::to_underlying' instead of 'static_cast' for 'enum class' [modernize-use-to-underlying] | ||
| // CHECK-FIXES: unsigned int val = std::to_underlying(TypedEnum::First); | ||
| } | ||
|
|
||
| // Test case 9: Casting to unsigned - should warn | ||
| void test_unsigned_cast() { | ||
| unsigned value = static_cast<unsigned>(MyEnum::A); | ||
| // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: use 'std::to_underlying' instead of 'static_cast' for 'enum class' [modernize-use-to-underlying] | ||
| // CHECK-FIXES: unsigned value = std::to_underlying(MyEnum::A); | ||
| } | ||
|
|
||
| // Test case 10: Nested in function call - should warn | ||
| void some_function(int x) {} | ||
|
|
||
| void test_nested_call() { | ||
| some_function(static_cast<int>(MyEnum::A)); | ||
| // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: use 'std::to_underlying' instead of 'static_cast' for 'enum class' [modernize-use-to-underlying] | ||
| // CHECK-FIXES: some_function(std::to_underlying(MyEnum::A)); | ||
| } | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please add newline. |
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Useless comment. Same below.