Skip to content
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
581cc0e
This commit is to resolve the issue #24841
chaitanyav Jul 19, 2024
8bf94c6
Revert "Added options to readability-implicit-bool-conversion (#1200…
4m4n-x-B4w4ne Jan 24, 2025
eb4dd90
Merge branch 'llvm:main' into issue_24841
4m4n-x-B4w4ne Jan 24, 2025
4a87afe
Fixed formatting issues
4m4n-x-B4w4ne Jan 24, 2025
44d208e
Fixed Formatting issues
4m4n-x-B4w4ne Jan 24, 2025
c9a20ef
Fixed Formatting issue
4m4n-x-B4w4ne Jan 24, 2025
ec6a689
Fixed Formating issues
4m4n-x-B4w4ne Jan 24, 2025
c815e43
further improvements as suggested
4m4n-x-B4w4ne Jan 27, 2025
47217aa
Delete clang-tools-extra/clang-tidy/modernize/UseCppStyleCommentsChec…
4m4n-x-B4w4ne Jan 27, 2025
7150e04
Delete clang-tools-extra/clang-tidy/modernize/UseCppStyleCommentsCheck.h
4m4n-x-B4w4ne Jan 27, 2025
ba3c7bb
improvements as suggested
4m4n-x-B4w4ne Jan 27, 2025
3d02ecd
Fixed Formatting issues
4m4n-x-B4w4ne Jan 27, 2025
7b657c4
Fixed Formatting issues
4m4n-x-B4w4ne Jan 27, 2025
2deb9d2
Fixed more formatting issues
4m4n-x-B4w4ne Jan 28, 2025
e9c899f
Added Options for Doxygen Comments
4m4n-x-B4w4ne Feb 2, 2025
21d6a41
ReadabilityTidyModule Sorted Alphabetically
4m4n-x-B4w4ne Feb 2, 2025
375ebce
Fixed to remove the warning.
4m4n-x-B4w4ne Feb 2, 2025
369aff7
Merge branch 'main' into issue_24841
4m4n-x-B4w4ne Feb 2, 2025
1f9a781
Fixed Some Formatting issues
4m4n-x-B4w4ne Feb 2, 2025
0f7b71f
Merge branch 'llvm:main' into issue_24841
4m4n-x-B4w4ne Feb 8, 2025
a02263f
Revert "Merge branch 'llvm:main' into issue_24841"
4m4n-x-B4w4ne Feb 8, 2025
b5f255f
Improved Logic and added new test file
4m4n-x-B4w4ne Feb 8, 2025
e93a072
Reapply "Merge branch 'llvm:main' into issue_24841"
4m4n-x-B4w4ne Feb 8, 2025
7e5439d
fmt'
4m4n-x-B4w4ne Feb 8, 2025
0dfe661
further modifications
4m4n-x-B4w4ne Feb 17, 2025
cc9249d
fmt'
4m4n-x-B4w4ne Feb 17, 2025
43aff62
fmt'
4m4n-x-B4w4ne Mar 15, 2025
2d4aee8
Merge branch 'main' into issue_24841
4m4n-x-B4w4ne Mar 15, 2025
5ffdc17
fmt'
4m4n-x-B4w4ne Mar 15, 2025
78fc4c9
fmt'
4m4n-x-B4w4ne Mar 15, 2025
cdb6b9a
fmt'
4m4n-x-B4w4ne Mar 16, 2025
d027247
added override
4m4n-x-B4w4ne Mar 16, 2025
84caead
Update clang-tools-extra/docs/ReleaseNotes.rst
4m4n-x-B4w4ne Mar 20, 2025
0935e58
Update clang-tools-extra/docs/clang-tidy/checks/readability/use-cpp-s…
4m4n-x-B4w4ne Mar 20, 2025
317ee60
Update use-cpp-style-comments.rst
4m4n-x-B4w4ne Jun 3, 2025
d8d3d2c
Update clang-tools-extra/test/clang-tidy/checkers/readability/use-cpp…
4m4n-x-B4w4ne Jun 3, 2025
884356f
Update clang-tools-extra/docs/clang-tidy/checks/readability/use-cpp-s…
4m4n-x-B4w4ne Jun 3, 2025
eb05ff8
Update UseCppStyleCommentsCheck.cpp
4m4n-x-B4w4ne Jun 8, 2025
5e91004
Update UseCppStyleCommentsCheck.cpp
4m4n-x-B4w4ne Jun 8, 2025
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/modernize/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ add_clang_library(clangTidyModernizeModule STATIC
UseAutoCheck.cpp
UseBoolLiteralsCheck.cpp
UseConstraintsCheck.cpp
UseCppStyleCommentsCheck.cpp
UseDefaultMemberInitCheck.cpp
UseDesignatedInitializersCheck.cpp
UseEmplaceCheck.cpp
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
#include "UseAutoCheck.h"
#include "UseBoolLiteralsCheck.h"
#include "UseConstraintsCheck.h"
#include "UseCppStyleCommentsCheck.h"
#include "UseDefaultMemberInitCheck.h"
#include "UseDesignatedInitializersCheck.h"
#include "UseEmplaceCheck.h"
Expand Down Expand Up @@ -107,6 +108,8 @@ class ModernizeModule : public ClangTidyModule {
"modernize-use-bool-literals");
CheckFactories.registerCheck<UseConstraintsCheck>(
"modernize-use-constraints");
CheckFactories.registerCheck<UseCppStyleCommentsCheck>(
"modernize-use-cpp-style-comments");
CheckFactories.registerCheck<UseDefaultMemberInitCheck>(
"modernize-use-default-member-init");
CheckFactories.registerCheck<UseEmplaceCheck>("modernize-use-emplace");
Expand Down
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 @@ -57,6 +57,7 @@ add_clang_library(clangTidyReadabilityModule STATIC
UniqueptrDeleteReleaseCheck.cpp
UppercaseLiteralSuffixCheck.cpp
UseAnyOfAllOfCheck.cpp
UseCppStyleCommentsCheck.cpp
UseStdMinMaxCheck.cpp

LINK_LIBS
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
#include "UniqueptrDeleteReleaseCheck.h"
#include "UppercaseLiteralSuffixCheck.h"
#include "UseAnyOfAllOfCheck.h"
#include "UseCppStyleCommentsCheck.h"
#include "UseStdMinMaxCheck.h"

namespace clang::tidy {
Expand Down Expand Up @@ -146,6 +147,8 @@ class ReadabilityModule : public ClangTidyModule {
"readability-static-definition-in-anonymous-namespace");
CheckFactories.registerCheck<StringCompareCheck>(
"readability-string-compare");
CheckFactories.registerCheck<UseCppStyleCommentsCheck>(
"readability-use-cpp-style-comments");
CheckFactories.registerCheck<readability::NamedParameterCheck>(
"readability-named-parameter");
CheckFactories.registerCheck<NonConstParameterCheck>(
Expand Down
136 changes: 136 additions & 0 deletions clang-tools-extra/clang-tidy/readability/UseCppStyleCommentsCheck.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
//===--- UseCppStyleCommentsCheck.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 "UseCppStyleCommentsCheck.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"
#include "clang/Lex/Preprocessor.h"
#include <sstream.h>

using namespace clang::ast_matchers;

namespace clang::tidy::readability {
class UseCppStyleCommentsCheck::CStyleCommentHandler : public CommentHandler {
public:
CStyleCommentHandler(UseCppStyleCommentsCheck &Check)
: Check(Check),
CStyleCommentMatch(
"^[ \t]*/\\*+[ \t\r\n]*(.*[ \t\r\n]*)*[ \t\r\n]*\\*+/[ \t\r\n]*$") {
}

std::string convertToCppStyleComment(const SourceManager &SM,
const SourceRange &Range) {
const StringRef CommentText = Lexer::getSourceText(
CharSourceRange::getTokenRange(Range), SM, LangOptions());

std::string InnerText = CommentText.str();
InnerText.erase(0, 2);
InnerText.erase(InnerText.size() - 2, 2);

std::string Result;
std::istringstream Stream(InnerText);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

avoid using istringstream , thats heavy to construct due to locales, just split string by '\n or \r'

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done Thanks! Can you please Review it?

std::string Line;

if (std::getline(Stream, Line)) {
const size_t StartPos = Line.find_first_not_of(" \t");
if (StartPos != std::string::npos) {
Line = Line.substr(StartPos);
} else {
Line.clear();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

avoid text copy, instead of generate list of "ranges to be replaced" and then generate FixIt for every of them

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done Thanks! Can you please Review it?

}
Result += "// " + Line;
}

while (std::getline(Stream, Line)) {
const size_t StartPos = Line.find_first_not_of(" \t");
if (StartPos != std::string::npos) {
Line = Line.substr(StartPos);
} else {
Line.clear();
}
Result += "\n// " + Line;
}
return Result;
}

bool CheckForInlineComments(Preprocessor &PP, SourceRange Range) {
const SourceManager &SM = PP.getSourceManager();
const SourceLocation CommentStart = Range.getBegin();
const SourceLocation CommentEnd = Range.getEnd();

unsigned StartLine = SM.getSpellingLineNumber(CommentStart);
unsigned EndLine = SM.getSpellingLineNumber(CommentEnd);

if (StartLine == EndLine) {
SourceLocation LineBegin =
SM.translateLineCol(SM.getFileID(CommentStart), StartLine, 1);
SourceLocation LineEnd =
SM.translateLineCol(SM.getFileID(CommentEnd), EndLine,
std::numeric_limits<unsigned>::max());
StringRef LineContent = Lexer::getSourceText(
CharSourceRange::getCharRange(LineBegin, LineEnd), SM,
PP.getLangOpts());
size_t CommentStartOffset = SM.getSpellingColumnNumber(CommentStart) - 1;
StringRef AfterComment =
LineContent.drop_front(CommentStartOffset + Text.size());

if (!AfterComment.trim().empty()) {
return true;
}
}
return false;
}

bool HandleComment(Preprocessor &PP, SourceRange Range) override {
const SourceManager &SM = PP.getSourceManager();

if (Range.getBegin().isMacroID() || SM.isInSystemHeader(Range.getBegin())) {
return false;
}

const StringRef Text = Lexer::getSourceText(
CharSourceRange::getCharRange(Range), SM, PP.getLangOpts());

SmallVector<StringRef> Matches;
if (!CStyleCommentMatch.match(Text, &Matches)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add also custom regexp as configuration option and called it ExcludedComents or something, in such case if this match comment, then exclude.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done Thanks! Can you please Review it?

Copy link
Contributor Author

@4m4n-x-B4w4ne 4m4n-x-B4w4ne Feb 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@PiotrZSL Can you please review it? like and tell me what next to be done.

return false;
}

if (CheckForInlineComments(PP, Range)) {
return false;
}

Check.diag(
Range.getBegin(),
"use C++ style comments '//' instead of C style comments '/*...*/'")
<< clang::FixItHint::CreateReplacement(
Range, convertToCppStyleComment(SM, Range));

return false;
}

private:
UseCppStyleCommentsCheck &Check;
llvm::Regex CStyleCommentMatch;
};

UseCppStyleCommentsCheck::UseCppStyleCommentsCheck(StringRef Name,
ClangTidyContext *Context)
: ClangTidyCheck(Name, Context),
Handler(std::make_unique<CStyleCommentHandler>(*this)) {}

void UseCppStyleCommentsCheck::registerPPCallbacks(
const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
PP->addCommentHandler(Handler.get());
}

void UseCppStyleCommentsCheck::check(const MatchFinder::MatchResult &Result) {}

UseCppStyleCommentsCheck::~UseCppStyleCommentsCheck() = default;
} // namespace clang::tidy::readability
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//===--- UseCppStyleCommentsCheck.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_USECPPSTYLECOMMENTSCHECK_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_USECPPSTYLECOMMENTSCHECK_H

#include "../ClangTidyCheck.h"

namespace clang::tidy::readability {
/// Detects C Style comments and suggests to use C++ style comments instead.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/readability/use-cpp-style-comments.html
class UseCppStyleCommentsCheck : public ClangTidyCheck {
public:
UseCppStyleCommentsCheck(StringRef Name, ClangTidyContext *Context);

~UseCppStyleCommentsCheck() override;

bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
return LangOpts.CPlusPlus;
}

void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP,
Preprocessor *ModuleExpanderPP) override;

void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove, since it's empty? Same for the .cpp file.


private:
class CStyleCommentHandler;
std::unique_ptr<CStyleCommentHandler> Handler;
};
} // namespace clang::tidy::readability

#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_USECPPSTYLECOMMENTSCHECK_H
5 changes: 5 additions & 0 deletions clang-tools-extra/docs/ReleaseNotes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,11 @@ New checks

Replace comparisons between signed and unsigned integers with their safe
C++20 ``std::cmp_*`` alternative, if available.

- New :doc:`modernize-use-cpp-style-comments
<clang-tidy/checks/modernize/use-cpp-style-comments>` check.

Detects C Style comments and suggests to use C++ style comments instead.

- New :doc:`portability-template-virtual-member-function
<clang-tidy/checks/portability/template-virtual-member-function>` check.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
.. title:: clang-tidy - use-cpp-style-comments

modernize-use-cpp-style-comments
================================

Replace C-style comments with C++-style comments.
C-style comments (``/* ... */``) are inherited from C, while C++ introduces
``//`` as a more concise, readable, and less error-prone alternative. Modern C++
guidelines recommend using C++-style comments for consistency and
maintainability. This check identifies and replaces C-style comments with
equivalent C++-style comments.

Examples:

Input:
.. code-block::c++
/* This is a single-line comment */
int x = 42; /* Inline comment */
/* This is a
multi-line comment */
Output:
.. code-block::c++
// This is a single-line comment
int x = 42; // Inline comment
// This is a
// multi-line comment
.. note::

Inline Comments are neither fixed nor warned.
Example:
.. code-block:: c++
int a = /* this is a comment */ 5;
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// RUN: %check_clang_tidy -std=c++11 %s modernize-use-cpp-style-comments %t -- --

// Single-line full C-style comment
static const int CONSTANT = 42; /* Important constant value */
// CHECK-MESSAGES: :[[@LINE-1]]:33: warning: use C++ style comments '//' instead of C style comments '/*...*/' [modernize-use-cpp-style-comments]
// CHECK-FIXES: static const int CONSTANT = 42; // Important constant value

// Inline comment that should NOT be transformed
int a = /* inline comment */ 5;

// Multiline full-line comment
/* This is a multiline comment
that spans several lines
and should be converted to C++ style */
// CHECK-MESSAGES: :[[@LINE-3]]:1: warning: use C++ style comments '//' instead of C style comments '/*...*/' [modernize-use-cpp-style-comments]
// CHECK-FIXES: // This is a multiline comment
// CHECK-FIXES: // that spans several lines
// CHECK-FIXES: // and should be converted to C++ style
void fnWithSomeBools(bool A,bool B) {}
// Function with parameter inline comments
void processData(int data /* input data */,
bool validate /* perform validation */) {
// These inline comments should NOT be transformed
fnWithSomeBools(/*ControlsA=*/ true, /*ControlsB=*/ false);
}

// Multiline comment with asterisk styling
/*******************************
* Block comment with asterisks
* Should be converted to C++ style
*******************************/
// CHECK-MESSAGES: :[[@LINE-4]]:1: warning: use C++ style comments '//' instead of C style comments '/*...*/' [modernize-use-cpp-style-comments]
// CHECK-FIXES: // ******************************
// CHECK-FIXES: // * Block comment with asterisks
// CHECK-FIXES: // * Should be converted to C++ style
// CHECK-FIXES: // ******************************
int calculateSomething() { return 1;}
// Comment at end of complex line
int complexCalculation = calculateSomething(); /* Result of complex calculation */
// CHECK-MESSAGES: :[[@LINE-1]]:48: warning: use C++ style comments '//' instead of C style comments '/*...*/' [modernize-use-cpp-style-comments]
// CHECK-FIXES: int complexCalculation = calculateSomething(); // Result of complex calculation

// Nested comments and edge cases
void edgeCaseFunction() {
int x = 10 /* First value */ + 20 /* Second value */; // Inline comments should not transform

/* Comment with special characters !@#$%^&*()_+ */
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use C++ style comments '//' instead of C style comments '/*...*/' [modernize-use-cpp-style-comments]
// CHECK-FIXES: // Comment with special characters !@#$%^&*()_+
}

// Multiline comment with various indentations
/* This comment is indented
and should preserve indentation when converted */
// CHECK-MESSAGES: :[[@LINE-2]]:5: warning: use C++ style comments '//' instead of C style comments '/*...*/' [modernize-use-cpp-style-comments]
// CHECK-FIXES: // This comment is indented
// CHECK-FIXES: // and should preserve indentation when converted

// Complex function with mixed comment types
void complexFunction() {
/* Full line comment at start of block */
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use C++ style comments '//' instead of C style comments '/*...*/' [modernize-use-cpp-style-comments]
// CHECK-FIXES: // Full line comment at start of block

int x = 10; /* Inline comment not to be transformed */
// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: use C++ style comments '//' instead of C style comments '/*...*/' [modernize-use-cpp-style-comments]
// CHECK-FIXES: int x = 10; // Inline comment not to be transformed
}
Loading