-
Notifications
You must be signed in to change notification settings - Fork 14.4k
[clang-tidy] Add portability-avoid-platform-specific-fundamental-types #146970
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
jj-marr
wants to merge
32
commits into
llvm:main
Choose a base branch
from
jj-marr:TypedefsOnly
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.
+870
−0
Open
Changes from 3 commits
Commits
Show all changes
32 commits
Select commit
Hold shift + click to select a range
3ef4feb
AvoidFundamentalIntegerTypesCheck
jj-marr 48598ef
Test typedefs properly
jj-marr 524fdd8
Document properly
jj-marr d5fd2e7
Rename files
jj-marr 25425cc
Other renaming for portability change
jj-marr 86787ec
Formatting fix
jj-marr c66668e
Make matchers more specific
jj-marr 1b314bb
Remove dead code
jj-marr 411d598
Fix doc
jj-marr b427df7
Fix issue on MSVC
jj-marr 5dd5c72
Merge comment with previous line
jj-marr 7c2031b
Add linter check to release notes
jj-marr 475f1b2
Update documentation
jj-marr 20e43d8
Fix redundant check
jj-marr 20e9b32
In progress work on float check
jj-marr f49a289
Declare const
jj-marr 143fcad
Synchronize with release notes
jj-marr 3c2ccd5
Attempt to format
jj-marr 40b8be3
Allow for int to not be warned
jj-marr 93c8489
Reduce some duplication
jj-marr 91eb765
vibecoding: not even once
jj-marr 723a76e
For each loop
jj-marr a30bedf
Format code
jj-marr 76125bb
Warn on chars
jj-marr 8258324
Fix header doc
jj-marr 8dd606b
Forgot to format
jj-marr 90c9887
Fix typo
jj-marr c487bf3
Fix formatting
jj-marr 09a762d
Declare as const
jj-marr a53b5bc
Add WarnOnInts documentation
jj-marr b525a7a
Enable all checks by default
jj-marr de662e8
Update clang-tools-extra/clang-tidy/portability/AvoidPlatformSpecific…
jj-marr 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
181 changes: 181 additions & 0 deletions
181
clang-tools-extra/clang-tidy/modernize/AvoidFundamentalIntegerTypesCheck.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,181 @@ | ||
//===--- AvoidFundamentalIntegerTypesCheck.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 "AvoidFundamentalIntegerTypesCheck.h" | ||
#include "clang/AST/ASTContext.h" | ||
#include "clang/ASTMatchers/ASTMatchFinder.h" | ||
#include "clang/ASTMatchers/ASTMatchers.h" | ||
|
||
using namespace clang::ast_matchers; | ||
|
||
namespace clang::tidy::modernize { | ||
|
||
namespace { | ||
|
||
AST_MATCHER(clang::TypeLoc, hasValidBeginLoc) { | ||
return Node.getBeginLoc().isValid(); | ||
} | ||
|
||
AST_MATCHER_P(clang::TypeLoc, hasType, | ||
clang::ast_matchers::internal::Matcher<clang::Type>, | ||
InnerMatcher) { | ||
const clang::Type *TypeNode = Node.getTypePtr(); | ||
return TypeNode != nullptr && | ||
InnerMatcher.matches(*TypeNode, Finder, Builder); | ||
} | ||
|
||
} // namespace | ||
|
||
AvoidFundamentalIntegerTypesCheck::AvoidFundamentalIntegerTypesCheck( | ||
StringRef Name, ClangTidyContext *Context) | ||
: ClangTidyCheck(Name, Context) {} | ||
|
||
bool AvoidFundamentalIntegerTypesCheck::isFundamentalIntegerType( | ||
const Type *T) const { | ||
if (!T->isBuiltinType()) | ||
return false; | ||
|
||
const auto *BT = T->getAs<BuiltinType>(); | ||
if (!BT) | ||
return false; | ||
|
||
switch (BT->getKind()) { | ||
case BuiltinType::Int: | ||
case BuiltinType::UInt: | ||
case BuiltinType::Short: | ||
case BuiltinType::UShort: | ||
case BuiltinType::Long: | ||
case BuiltinType::ULong: | ||
case BuiltinType::LongLong: | ||
case BuiltinType::ULongLong: | ||
return true; | ||
default: | ||
return false; | ||
} | ||
} | ||
|
||
bool AvoidFundamentalIntegerTypesCheck::isSemanticType(const Type *T) const { | ||
if (!T->isBuiltinType()) | ||
return false; | ||
|
||
const auto *BT = T->getAs<BuiltinType>(); | ||
if (!BT) | ||
return false; | ||
|
||
switch (BT->getKind()) { | ||
case BuiltinType::Bool: | ||
case BuiltinType::Char_S: | ||
case BuiltinType::Char_U: | ||
case BuiltinType::SChar: | ||
case BuiltinType::UChar: | ||
case BuiltinType::WChar_S: | ||
case BuiltinType::WChar_U: | ||
case BuiltinType::Char8: | ||
case BuiltinType::Char16: | ||
case BuiltinType::Char32: | ||
return true; | ||
default: | ||
return false; | ||
} | ||
} | ||
|
||
void AvoidFundamentalIntegerTypesCheck::registerMatchers(MatchFinder *Finder) { | ||
// Match variable declarations with fundamental integer types | ||
Finder->addMatcher( | ||
varDecl().bind("var_decl"), | ||
this); | ||
|
||
// Match function declarations with fundamental integer return types | ||
Finder->addMatcher( | ||
functionDecl().bind("func_decl"), | ||
this); | ||
|
||
// Match function parameters with fundamental integer types | ||
Finder->addMatcher( | ||
parmVarDecl().bind("param_decl"), | ||
this); | ||
|
||
// Match field declarations with fundamental integer types | ||
Finder->addMatcher( | ||
fieldDecl().bind("field_decl"), | ||
this); | ||
|
||
// Match typedef declarations to check their underlying types | ||
Finder->addMatcher( | ||
typedefDecl().bind("typedef_decl"), | ||
this); | ||
|
||
Finder->addMatcher( | ||
typeAliasDecl().bind("alias_decl"), | ||
this); | ||
} | ||
|
||
void AvoidFundamentalIntegerTypesCheck::check( | ||
const MatchFinder::MatchResult &Result) { | ||
SourceLocation Loc; | ||
QualType QT; | ||
std::string DeclType; | ||
|
||
if (const auto *VD = Result.Nodes.getNodeAs<VarDecl>("var_decl")) { | ||
Loc = VD->getLocation(); | ||
QT = VD->getType(); | ||
DeclType = "variable"; | ||
} else if (const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("func_decl")) { | ||
Loc = FD->getLocation(); | ||
QT = FD->getReturnType(); | ||
DeclType = "function return type"; | ||
} else if (const auto *PD = Result.Nodes.getNodeAs<ParmVarDecl>("param_decl")) { | ||
Loc = PD->getLocation(); | ||
QT = PD->getType(); | ||
DeclType = "function parameter"; | ||
} else if (const auto *FD = Result.Nodes.getNodeAs<FieldDecl>("field_decl")) { | ||
Loc = FD->getLocation(); | ||
QT = FD->getType(); | ||
DeclType = "field"; | ||
} else if (const auto *TD = Result.Nodes.getNodeAs<TypedefDecl>("typedef_decl")) { | ||
Loc = TD->getLocation(); | ||
QT = TD->getUnderlyingType(); | ||
DeclType = "typedef"; | ||
} else if (const auto *AD = Result.Nodes.getNodeAs<TypeAliasDecl>("alias_decl")) { | ||
Loc = AD->getLocation(); | ||
QT = AD->getUnderlyingType(); | ||
DeclType = "type alias"; | ||
} else { | ||
return; | ||
} | ||
|
||
if (Loc.isInvalid() || QT.isNull()) | ||
return; | ||
|
||
// Check if the type is already a typedef - if so, don't warn | ||
// since the user is already using a typedef (which is what we want) | ||
if (QT->getAs<TypedefType>()) { | ||
return; | ||
} | ||
|
||
const Type *T = QT.getCanonicalType().getTypePtr(); | ||
if (!T) | ||
return; | ||
|
||
// Skip if not a fundamental integer type | ||
if (!isFundamentalIntegerType(T)) | ||
return; | ||
|
||
// Skip semantic types | ||
if (isSemanticType(T)) | ||
return; | ||
|
||
// Get the type name for the diagnostic | ||
std::string TypeName = QT.getAsString(); | ||
|
||
diag(Loc, "avoid using platform-dependent fundamental integer type '%0'; " | ||
"consider using a typedef or fixed-width type instead") | ||
<< TypeName; | ||
} | ||
|
||
} // namespace clang::tidy::modernize |
44 changes: 44 additions & 0 deletions
44
clang-tools-extra/clang-tidy/modernize/AvoidFundamentalIntegerTypesCheck.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,44 @@ | ||
//===--- AvoidFundamentalIntegerTypesCheck.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_MODERNIZE_AVOIDFUNDAMENTALINTEGERTYPESCHECK_H | ||
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_AVOIDFUNDAMENTALINTEGERTYPESCHECK_H | ||
|
||
#include "../ClangTidyCheck.h" | ||
|
||
namespace clang::tidy::modernize { | ||
|
||
/// Find fundamental integer types and recommend using typedefs or fixed-width types. | ||
/// | ||
/// Detects fundamental integer types (int, short, long, long long, and their | ||
/// unsigned variants) and warns against their use due to platform-dependent | ||
/// behavior. Excludes semantic types like char, bool, wchar_t, char16_t, | ||
/// char32_t, size_t, and ptrdiff_t. | ||
/// | ||
/// For the user-facing documentation see: | ||
/// http://clang.llvm.org/extra/clang-tidy/checks/modernize/avoid-fundamental-integer-types.html | ||
class AvoidFundamentalIntegerTypesCheck : public ClangTidyCheck { | ||
public: | ||
AvoidFundamentalIntegerTypesCheck(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 { | ||
return LangOpts.CPlusPlus11; | ||
} | ||
std::optional<TraversalKind> getCheckTraversalKind() const override { | ||
return TK_IgnoreUnlessSpelledInSource; | ||
} | ||
|
||
private: | ||
bool isFundamentalIntegerType(const Type *T) const; | ||
bool isSemanticType(const Type *T) const; | ||
}; | ||
|
||
} // namespace clang::tidy::modernize | ||
|
||
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_AVOIDFUNDAMENTALINTEGERTYPESCHECK_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
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
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
111 changes: 111 additions & 0 deletions
111
...ools-extra/docs/clang-tidy/checks/modernize/avoid-fundamental-integer-types.rst
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,111 @@ | ||
.. title:: clang-tidy - modernize-avoid-fundamental-integer-types | ||
|
||
modernize-avoid-fundamental-integer-types | ||
========================================== | ||
|
||
Finds fundamental integer types and recommends using typedefs or fixed-width types instead. | ||
|
||
This check detects fundamental integer types (``int``, ``short``, ``long``, ``long long``, and their | ||
``unsigned`` variants) and warns against their use due to non-standard platform-dependent behavior. | ||
For example, ``long`` is 64 bits on Linux but 32 bits on Windows. There is no standard rationale or | ||
intent for the sizes of these types. | ||
|
||
Instead of fundamental types, use fixed-width types such as ``int32_t`` or implementation-defined | ||
types with standard semantics, e.g. ``int_fast32_t`` for the fastest integer type greater than or | ||
equal to 32 bits. | ||
|
||
Examples | ||
-------- | ||
|
||
.. code-block:: c++ | ||
|
||
// Bad: platform-dependent fundamental types | ||
int global_int = 42; | ||
short global_short = 10; | ||
long global_long = 100L; | ||
unsigned long global_unsigned_long = 100UL; | ||
|
||
void function_with_int_param(int param) { | ||
// ... | ||
} | ||
|
||
int function_returning_int() { | ||
return 42; | ||
} | ||
|
||
struct MyStruct { | ||
int member_int; | ||
long member_long; | ||
}; | ||
|
||
.. code-block:: c++ | ||
|
||
// Good: use fixed-width types or typedefs | ||
#include <cstdint> | ||
|
||
int32_t global_int32 = 42; | ||
int16_t global_int16 = 10; | ||
int64_t global_int64 = 100L; | ||
uint64_t global_uint64 = 100UL; | ||
|
||
void function_with_int32_param(int32_t param) { | ||
// ... | ||
} | ||
|
||
int32_t function_returning_int32() { | ||
return 42; | ||
} | ||
|
||
struct MyStruct { | ||
int32_t member_int32; | ||
int64_t member_int64; | ||
}; | ||
|
||
The check will also warn about typedef declarations that use fundamental types as their underlying type: | ||
|
||
.. code-block:: c++ | ||
|
||
// Bad: typedef using fundamental type | ||
typedef long long MyLongType; | ||
using MyIntType = int; | ||
|
||
.. code-block:: c++ | ||
|
||
// Good: use descriptive names or fixed-width types | ||
typedef int64_t TimestampType; | ||
using CounterType = uint32_t; | ||
|
||
Rationale | ||
--------- | ||
|
||
Fundamental integer types have platform-dependent sizes and behavior: | ||
|
||
- ``int`` is typically 32 bits on modern platforms but is only guaranteed to be 16 bits by the spec | ||
- ``long int`` is 32 bits on Windows but 64 bits on most Unix systems | ||
|
||
The C++ specification does not define these types beyond their minimum sizes. That means they can | ||
communicate intent in non-standard ways and are often needlessly incompatible. For example, ``int`` | ||
was traditionally the word size of a given processor in 16-bit and 32-bit computing and was a | ||
reasonable default for performance. This is no longer true on modern 64-bit computers, but the size | ||
of ``int`` remains fixed at 32 bits for backwards compatibility with code that relied on a 32-bit | ||
implementation of ``int``. | ||
|
||
If code is explicitly relying on the size of an ``int`` being 32 bits, it is better to say so in | ||
the typename with ``int32_t``. Otherwise, use an appropriate implementation-defined type that | ||
communicates your intent. | ||
|
||
Types Not Flagged | ||
----------------- | ||
|
||
The following types are intentionally not flagged: | ||
|
||
- ``char``, ``signed char``, ``unsigned char`` (character types) | ||
- ``bool`` (boolean type) | ||
- Standard library typedefs like ``size_t``, ``ptrdiff_t``, or ``uint32_t``. | ||
- Already typedef'd types, though the check will flag the typedef itself | ||
|
||
``char`` is excluded because it is implementation-defined to always be 1 byte, regardless of the | ||
platform's definition of a byte. | ||
|
||
``bool`` is excluded because it can only be true or false, and is not vulnerable to overflow or | ||
narrowing issues that occur as a result of using implementation-defined types. |
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.