-
Notifications
You must be signed in to change notification settings - Fork 13.6k
[clang-tidy] Add new check bugprone-unintended-char-ostream-output #127720
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
[clang-tidy] Add new check bugprone-unintended-char-ostream-output #127720
Conversation
It wants to find unintended character output from and to an ostream. e.g. uint8_t v = 9; std::cout << v;
@llvm/pr-subscribers-clang-tools-extra @llvm/pr-subscribers-clang-tidy Author: Congcong Cai (HerrCai0907) ChangesIt wants to find unintended character output from uint8_t v = 9;
std::cout << v; Full diff: https://github.com/llvm/llvm-project/pull/127720.diff 8 Files Affected:
diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index c5f0b5b28418f..0a3376949b6e5 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -90,6 +90,7 @@
#include "UndelegatedConstructorCheck.h"
#include "UnhandledExceptionAtNewCheck.h"
#include "UnhandledSelfAssignmentCheck.h"
+#include "UnintendedCharOstreamOutputCheck.h"
#include "UniquePtrArrayMismatchCheck.h"
#include "UnsafeFunctionsCheck.h"
#include "UnusedLocalNonTrivialVariableCheck.h"
@@ -147,6 +148,8 @@ class BugproneModule : public ClangTidyModule {
"bugprone-incorrect-enable-if");
CheckFactories.registerCheck<IncorrectEnableSharedFromThisCheck>(
"bugprone-incorrect-enable-shared-from-this");
+ CheckFactories.registerCheck<UnintendedCharOstreamOutputCheck>(
+ "bugprone-unintended-char-ostream-output");
CheckFactories.registerCheck<ReturnConstRefFromParameterCheck>(
"bugprone-return-const-ref-from-parameter");
CheckFactories.registerCheck<SwitchMissingDefaultCaseCheck>(
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index e8309c68b7fca..9758d7259bf65 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -29,6 +29,7 @@ add_clang_library(clangTidyBugproneModule STATIC
InaccurateEraseCheck.cpp
IncorrectEnableIfCheck.cpp
IncorrectEnableSharedFromThisCheck.cpp
+ UnintendedCharOstreamOutputCheck.cpp
ReturnConstRefFromParameterCheck.cpp
SuspiciousStringviewDataUsageCheck.cpp
SwitchMissingDefaultCaseCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp
new file mode 100644
index 0000000000000..7c54ef1486b2f
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp
@@ -0,0 +1,70 @@
+//===--- UnintendedCharOstreamOutputCheck.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 "UnintendedCharOstreamOutputCheck.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+
+// check if the type is unsigned char or signed char
+AST_MATCHER(Type, isNumericChar) {
+ const auto *BT = dyn_cast<BuiltinType>(&Node);
+ if (BT == nullptr)
+ return false;
+ const BuiltinType::Kind K = BT->getKind();
+ return K == BuiltinType::UChar || K == BuiltinType::SChar;
+}
+
+// check if the type is char
+AST_MATCHER(Type, isChar) {
+ const auto *BT = dyn_cast<BuiltinType>(&Node);
+ if (BT == nullptr)
+ return false;
+ const BuiltinType::Kind K = BT->getKind();
+ return K == BuiltinType::Char_U || K == BuiltinType::Char_S;
+}
+
+} // namespace
+
+void UnintendedCharOstreamOutputCheck::registerMatchers(MatchFinder *Finder) {
+ auto BasicOstream =
+ cxxRecordDecl(hasName("::std::basic_ostream"),
+ // only basic_ostream<char, Traits> has overload operator<<
+ // with char / unsigned char / signed char
+ classTemplateSpecializationDecl(
+ hasTemplateArgument(0, refersToType(isChar()))));
+ Finder->addMatcher(
+ cxxOperatorCallExpr(
+ hasOverloadedOperatorName("<<"),
+ hasLHS(hasType(hasUnqualifiedDesugaredType(
+ recordType(hasDeclaration(cxxRecordDecl(
+ anyOf(BasicOstream, isDerivedFrom(BasicOstream)))))))),
+ hasRHS(hasType(hasUnqualifiedDesugaredType(isNumericChar()))))
+ .bind("x"),
+ this);
+}
+
+void UnintendedCharOstreamOutputCheck::check(
+ const MatchFinder::MatchResult &Result) {
+ const auto *Call = Result.Nodes.getNodeAs<CXXOperatorCallExpr>("x");
+ const Expr *Value = Call->getArg(1);
+ diag(Call->getOperatorLoc(),
+ "(%0 passed to 'operator<<' outputs as character instead of integer. "
+ "cast to 'unsigned' to print numeric value or cast to 'char' to print "
+ "as character)")
+ << Value->getType() << Value->getSourceRange();
+}
+
+} // namespace clang::tidy::bugprone
diff --git a/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.h b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.h
new file mode 100644
index 0000000000000..071baac3216c0
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.h
@@ -0,0 +1,34 @@
+//===--- UnintendedCharOstreamOutputCheck.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_BUGPRONE_UNINTENDEDCHAROSTREAMOUTPUTCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_UNINTENDEDCHAROSTREAMOUTPUTCHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang::tidy::bugprone {
+
+/// Finds unintended character output from `unsigned char` and `signed char` to
+/// an ostream.
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone/unintended-char-ostream-output.html
+class UnintendedCharOstreamOutputCheck : public ClangTidyCheck {
+public:
+ UnintendedCharOstreamOutputCheck(StringRef Name, ClangTidyContext *Context)
+ : ClangTidyCheck(Name, 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.CPlusPlus;
+ }
+};
+
+} // namespace clang::tidy::bugprone
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_UNINTENDEDCHAROSTREAMOUTPUTCHECK_H
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst
index 6b8fe22242417..57f37c8e02e2e 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -91,6 +91,12 @@ Improvements to clang-tidy
New checks
^^^^^^^^^^
+- New :doc:`bugprone-unintended-char-ostream-output
+ <clang-tidy/checks/bugprone/unintended-char-ostream-output>` check.
+
+ Finds unintended character output from `unsigned char` and `signed char` to an
+ ostream.
+
New check aliases
^^^^^^^^^^^^^^^^^
diff --git a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
new file mode 100644
index 0000000000000..1e60698a5d445
--- /dev/null
+++ b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
@@ -0,0 +1,30 @@
+.. title:: clang-tidy - bugprone-unintended-char-ostream-output
+
+bugprone-unintended-char-ostream-output
+=======================================
+
+Finds unintended character output from `unsigned char` and `signed char` to an
+``ostream``.
+
+Normally, when ``unsigned char (uint8_t)`` or ``signed char (int8_t)`` is used, it
+is more likely a number than a character. However, when it is passed directly to
+``std::ostream``'s ``operator<<``, resulting in character-based output instead
+of numeric value. This often contradicts the developer's intent to print
+integer values.
+
+.. code-block:: c++
+
+ uint8_t v = 9;
+ std::cout << v; // output '\t' instead of '9'
+
+It could be fixed as
+
+.. code-block:: c++
+
+ std::cout << (uint32_t)v;
+
+Or cast to char to explicitly indicate the intent
+
+.. code-block:: c++
+
+ std::cout << (char)v;
diff --git a/clang-tools-extra/docs/clang-tidy/checks/list.rst b/clang-tools-extra/docs/clang-tidy/checks/list.rst
index 7b9b905ef7671..9306dfe95fa45 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -158,6 +158,7 @@ Clang-Tidy Checks
:doc:`bugprone-undelegated-constructor <bugprone/undelegated-constructor>`,
:doc:`bugprone-unhandled-exception-at-new <bugprone/unhandled-exception-at-new>`,
:doc:`bugprone-unhandled-self-assignment <bugprone/unhandled-self-assignment>`,
+ :doc:`bugprone-unintended-char-ostream-output <bugprone/unintended-char-ostream-output>`,
:doc:`bugprone-unique-ptr-array-mismatch <bugprone/unique-ptr-array-mismatch>`, "Yes"
:doc:`bugprone-unsafe-functions <bugprone/unsafe-functions>`,
:doc:`bugprone-unused-local-non-trivial-variable <bugprone/unused-local-non-trivial-variable>`,
diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output.cpp
new file mode 100644
index 0000000000000..fd2382dcd730c
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output.cpp
@@ -0,0 +1,70 @@
+// RUN: %check_clang_tidy %s bugprone-unintended-char-ostream-output %t
+
+namespace std {
+
+template <class _CharT, class _Traits = void> class basic_ostream {
+public:
+ basic_ostream &operator<<(int);
+ basic_ostream &operator<<(unsigned int);
+};
+
+template <class CharT, class Traits>
+basic_ostream<CharT, Traits> &operator<<(basic_ostream<CharT, Traits> &, CharT);
+template <class CharT, class Traits>
+basic_ostream<CharT, Traits> &operator<<(basic_ostream<CharT, Traits> &, char);
+template <class _Traits>
+basic_ostream<char, _Traits> &operator<<(basic_ostream<char, _Traits> &, char);
+template <class _Traits>
+basic_ostream<char, _Traits> &operator<<(basic_ostream<char, _Traits> &,
+ signed char);
+template <class _Traits>
+basic_ostream<char, _Traits> &operator<<(basic_ostream<char, _Traits> &,
+ unsigned char);
+
+using ostream = basic_ostream<char>;
+
+
+} // namespace std
+
+class A : public std::ostream {};
+
+void origin_ostream(std::ostream &os) {
+ unsigned char unsigned_value = 9;
+ os << unsigned_value;
+ // CHECK-MESSAGES: [[@LINE-1]]:6: warning: ('unsigned char' passed to
+ // 'operator<<' outputs as character instead of integer
+
+ signed char signed_value = 9;
+ os << signed_value;
+ // CHECK-MESSAGES: [[@LINE-1]]:6: warning: ('signed char' passed to
+ // 'operator<<' outputs as character instead of integer
+
+ char char_value = 9;
+ os << char_value;
+}
+
+void based_on_ostream(A &os) {
+ unsigned char unsigned_value = 9;
+ os << unsigned_value;
+ // CHECK-MESSAGES: [[@LINE-1]]:6: warning: ('unsigned char' passed to
+ // 'operator<<' outputs as character instead of integer
+
+ signed char signed_value = 9;
+ os << signed_value;
+ // CHECK-MESSAGES: [[@LINE-1]]:6: warning: ('signed char' passed to
+ // 'operator<<' outputs as character instead of integer
+
+ char char_value = 9;
+ os << char_value;
+}
+
+void based_on_ostream(std::basic_ostream<unsigned char> &os) {
+ unsigned char unsigned_value = 9;
+ os << unsigned_value;
+
+ signed char signed_value = 9;
+ os << signed_value;
+
+ char char_value = 9;
+ os << char_value;
+}
|
clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
Outdated
Show resolved
Hide resolved
clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
Outdated
Show resolved
Hide resolved
clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output.cpp
Outdated
Show resolved
Hide resolved
03eacf4
to
9033197
Compare
clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
Outdated
Show resolved
Hide resolved
clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
Outdated
Show resolved
Hide resolved
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.
Overall looks fine for me, just few things to point out.
"%0 passed to 'operator<<' outputs as character instead of integer. " | ||
"cast to 'unsigned' to print numeric value or cast to 'char' to print " | ||
"as character") | ||
<< Value->getType() << Value->getSourceRange(); |
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.
You could generate auto-fixes, easiest way is to insert "+" character before such, in that case it will be cast to int
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.
That's a fairly obscure solution, relying on implicit arithmetic promotions. It's banned in some coding guidelines (e.g. MISRA). Maybe just add an explicit static_cast<int>
? Otherwise give the option to the user to choose what datatype to cast to, defaulting to int
.
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.
The problem with int
versus unsigned int
is that in case you're on a platform where sizeof(char) == sizeof(int)
then casting a value that happens to encode to a negative integer will result in the printing of a negative number. Not sure if this is something intentional.
(Nevertheless, I would prefer if the warning said unsigned int
instead of just unsigned
. It's non-trivial to know that unsigned
alone is perfectly fine and actually means the same thing as unsinged int
.)
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.
I think easiest is to just let the user decide what type they want to use, keeping some sane default (unsigned int
is fine IMO).
Some guidelines also ban the usage of built-in types like int
and require you to use std::int32_t
instead to be explicit. Having an option would allow the user to specify that.
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.
For me, it is more clearer to cast unsigned char to unsigned int and signed char to int. This can avoid that when converting unsigned char to int, people are not sure whether the result of 255 is -1 or 255.
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.
Given the range only suggesting int
should be safe. Adding unsigned
in case the underlying type would make it more clearer though.
As in other cases I think it should be coding guideline agnostic and suggest the least intrusive (e.g. std::int32_t
requires the <cstdint>
include). But let's not start that discussion again...
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.
requires the include
Fair point. Perhaps just cast to int
is the best compromise. It is also what unary plus does. If users need more flexibility we can add an option 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.
option is already added.
clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output.cpp
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp
Outdated
Show resolved
Hide resolved
|
||
.. code-block:: c++ | ||
|
||
std::cout << static_cast<uint32_t>(v); |
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.
or
std::cout << +v;
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.
I think it is quiet magic and relies on the developer's familiarity with the C++ specification
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.
It is "magic" but I think it might make sense to make sure that the warning is not triggered by it.
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.
Absolutely, this is a valid code pattern (magic or not) that the tool should not warn about.
In the docs, if wanted, we could mention both cases as examples, and also explain that unary plus leads to the same result as static_cast<int>
.
clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output.cpp
Show resolved
Hide resolved
…har-ostream-output.rst Co-authored-by: whisperity <[email protected]>
clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output.cpp
Show resolved
Hide resolved
clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
Outdated
Show resolved
Hide resolved
…lvm#127720) It wants to find unintended character output from `uint8_t` and `int8_t` to an ostream. e.g. ```c++ uint8_t v = 9; std::cout << v; ``` --------- Co-authored-by: whisperity <[email protected]>
Some thoughts based on the warnings I am seeing in actual code. Another way to fix this could be using I am seeing this with an enum type which might be valid, working code but have not looked into it yet. The fix-it is problematic if it is a templated type and should probably be omitted in that case: #include <cstdint>
#include <sstream>
template<typename T>
void func(const T& data)
{
std::ostringstream ostr;
ostr << data;
}
void f()
{
func((char)0);
func((int8_t)0);
func("");
}
|
The warnings in question were correct. It exposed a behavior change introduced by fixing |
It wants to find unintended character output from
uint8_t
andint8_t
to an ostream.e.g.