Skip to content
Open
Show file tree
Hide file tree
Changes from 32 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/readability/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,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 @@ -61,6 +61,7 @@
#include "UniqueptrDeleteReleaseCheck.h"
#include "UppercaseLiteralSuffixCheck.h"
#include "UseAnyOfAllOfCheck.h"
#include "UseCppStyleCommentsCheck.h"
#include "UseStdMinMaxCheck.h"

namespace clang::tidy {
Expand Down Expand Up @@ -173,6 +174,8 @@ class ReadabilityModule : public ClangTidyModule {
"readability-uppercase-literal-suffix");
CheckFactories.registerCheck<UseAnyOfAllOfCheck>(
"readability-use-anyofallof");
CheckFactories.registerCheck<UseCppStyleCommentsCheck>(
"readability-use-cpp-style-comments");
CheckFactories.registerCheck<UseStdMinMaxCheck>(
"readability-use-std-min-max");
}
Expand Down
188 changes: 188 additions & 0 deletions clang-tools-extra/clang-tidy/readability/UseCppStyleCommentsCheck.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
//===--- 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 <optional>

using namespace clang::ast_matchers;

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

StringRef getExcludedCommentsRegex() const { return ExcludedComments; }

bool isExcludeDoxygen() const { return ExcludeDoxygen; }

void convertToCppStyleCommentFixes(const SourceManager &SM,
const SourceRange &Range,
SmallVectorImpl<FixItHint> &FixIts) {
StringRef CommentText = Lexer::getSourceText(
CharSourceRange::getTokenRange(Range), SM, LangOptions());

CommentText = CommentText.drop_front(2).drop_back(2);
const SourceLocation StartLoc = Range.getBegin();
const FileID FID = SM.getFileID(StartLoc);
unsigned LineNo = SM.getSpellingLineNumber(StartLoc);
const unsigned StartCol = SM.getSpellingColumnNumber(StartLoc);
if (!CommentText.empty()) {
const size_t NewlinePos = CommentText.find('\n');

const StringRef Line = (NewlinePos == StringRef::npos)
? CommentText
: CommentText.substr(0, NewlinePos);

const SourceLocation LineStart =
SM.translateLineCol(FID, LineNo, StartCol);
const SourceLocation LineEnd = SM.translateLineCol(
FID, LineNo, std::numeric_limits<unsigned>::max());

FixIts.push_back(FixItHint::CreateReplacement(
CharSourceRange::getCharRange(LineStart, LineEnd),
"//" + Line.str()));

if (NewlinePos != StringRef::npos) {
CommentText = CommentText.substr(NewlinePos + 1);
LineNo++;
} else {
CommentText = "";
}
}
while (!CommentText.empty()) {
const size_t NewlinePos = CommentText.find('\n');

StringRef Line = (NewlinePos == StringRef::npos)
? CommentText
: CommentText.substr(0, NewlinePos);

const SourceLocation LineStart = SM.translateLineCol(FID, LineNo, 1);
const SourceLocation LineEnd = SM.translateLineCol(
FID, LineNo, std::numeric_limits<unsigned>::max());

if (Line.substr(0, 2) == " ") {
Line = Line.drop_front(2);
FixIts.push_back(FixItHint::CreateReplacement(
CharSourceRange::getCharRange(LineStart, LineEnd),
"//" + Line.str()));
} else {
FixIts.push_back(FixItHint::CreateReplacement(
CharSourceRange::getCharRange(LineStart, LineEnd),
"//" + Line.str()));
}

if (NewlinePos == StringRef::npos)
break;

CommentText = CommentText.substr(NewlinePos + 1);
LineNo++;
}
}

bool isDoxygenStyleComment(const StringRef &Text) {
StringRef Trimmed = Text.ltrim();
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
StringRef Trimmed = Text.ltrim();
const StringRef Trimmed = Text.ltrim();

return Trimmed.starts_with("/**") || Trimmed.starts_with("/*!") ||
Trimmed.starts_with("///") || Trimmed.starts_with("//!") ||
(Trimmed.starts_with("/*") &&
Trimmed.drop_front(2).starts_with("*"));
}

bool CheckForCodeAfterComment(Preprocessor &PP, SourceRange Range) {
const SourceManager &SM = PP.getSourceManager();
const SourceLocation CommentStart = Range.getBegin(),
CommentEnd = Range.getEnd();
const std::optional<Token> NextTok =
Lexer::findNextToken(CommentStart, SM, PP.getLangOpts());
if (!NextTok.has_value())
return false;

const std::string tokenSpelling =
Lexer::getSpelling(*NextTok, SM, PP.getLangOpts());
const unsigned lineNo = SM.getSpellingLineNumber(CommentEnd);
const SourceLocation loc = NextTok->getLocation();
const unsigned tokenLine = SM.getSpellingLineNumber(loc);
return lineNo == tokenLine;
}

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());

if (!ExcludedCommentMatch.isValid()) {
llvm::errs() << "Warning: Invalid regex pattern:" << ExcludedComments
<< ":for ExcludedComments\n";
} else if (ExcludedCommentMatch.match(Text)) {
return false;
}
if (ExcludeDoxygen && isDoxygenStyleComment(Text))
return false;

SmallVector<StringRef> Matches;
if (!CStyleCommentMatch.match(Text, &Matches))
return false;

if (CheckForCodeAfterComment(PP, Range))
return false;

SmallVector<FixItHint, 4> FixIts;
convertToCppStyleCommentFixes(SM, Range, FixIts);

auto D = Check.diag(
Range.getBegin(),
"use C++ style comments '//' instead of C style comments '/*...*/'");

for (const auto &Fix : FixIts)
Copy link
Contributor

Choose a reason for hiding this comment

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

ditto auto usage

D << Fix;

return false;
}

private:
UseCppStyleCommentsCheck &Check;
bool ExcludeDoxygen;
StringRef ExcludedComments;
llvm::Regex ExcludedCommentMatch;
llvm::Regex CStyleCommentMatch;
};

UseCppStyleCommentsCheck::UseCppStyleCommentsCheck(StringRef Name,
ClangTidyContext *Context)
: ClangTidyCheck(Name, Context),
Handler(std::make_unique<CStyleCommentHandler>(
*this, Options.get("ExcludeDoxygenStyleComments", false),
Options.get("ExcludedComments", "^$"))) {}

void UseCppStyleCommentsCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
Options.store(Opts, "ExcludeDoxygenStyleComments",
Handler->isExcludeDoxygen());
Options.store(Opts, "ExcludedComments", Handler->getExcludedCommentsRegex());
}
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,45 @@
//===--- 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"
#include <memory>

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.


void storeOptions(ClangTidyOptions::OptionMap &Opts) override;

private:
class CStyleCommentHandler;
std::unique_ptr<CStyleCommentHandler> Handler;
const bool ExcludeDoxygenStyleComments =
Copy link
Contributor

Choose a reason for hiding this comment

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

Typically these are initialized in the constructor initializer list

Options.get("ExcludeDoxygenStyleComments", false);
const StringRef ExcludedComments = Options.get("ExcludedComments", "^$");
};
} // 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 @@ -112,6 +112,11 @@ New checks
Finds potentially erroneous calls to ``reset`` method on smart pointers when
the pointee type also has a ``reset`` method.

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

Replace C-style comments with C++-style comments.

New check aliases
^^^^^^^^^^^^^^^^^

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 @@ -405,6 +405,7 @@ Clang-Tidy Checks
:doc:`readability-uniqueptr-delete-release <readability/uniqueptr-delete-release>`, "Yes"
:doc:`readability-uppercase-literal-suffix <readability/uppercase-literal-suffix>`, "Yes"
:doc:`readability-use-anyofallof <readability/use-anyofallof>`,
:doc:`readability-use-cpp-style-comments <readability/use-cpp-style-comments>`, "Yes"
:doc:`readability-use-std-min-max <readability/use-std-min-max>`, "Yes"
:doc:`zircon-temporary-objects <zircon/temporary-objects>`,

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
.. title:: clang-tidy - use-cpp-style-comments

readability-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.
Copy link
Contributor

Choose a reason for hiding this comment

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

warned about


Example:

.. code-block:: c++

int a = /* this is a comment */ 5;
Options
-------

.. option:: ExcludeDoxygenStyleComments

A boolean option that determines whether Doxygen-style comments should be excluded.
Default is `false`.

.. option:: ExcludedComments

A regex pattern that allows specifying certain comments to exclude from transformation.
By default, this option is set to `^$`, which means no comments are excluded.
You can provide a custom regex to exclude specific comments based on your needs.
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// RUN: %check_clang_tidy -std=c++11 %s readability-use-cpp-style-comments %t -config="{CheckOptions: [{key: readability-use-cpp-style-comments.ExcludeDoxygenStyleComments, value: true}]}"

// Tests for Doxygen comments with ExcludeDoxygenStyleComments enabled
/**
* This is a Doxygen comment for a function.
* It should NOT be transformed.
*/
void doxygenFunction1();

/*!
* This is another Doxygen-style comment.
* It should also NOT be transformed.
*/
void doxygenFunction2();

/**
* Multiline Doxygen comment describing parameters.
*
* @param x The first parameter.
* @param y The second parameter.
* @return A result value.
*/
int doxygenFunctionWithParams(int x, int y);

/*******************************
* Non-Doxygen block comments without markers
*******************************/
void DoxygenBlock();

/*!
* This is a single-line Doxygen comment.
* Should NOT be transformed.
*/
void singleLineDoxygen();
Loading