| 1 |
//===--- NamespaceCommentCheck.cpp - clang-tidy ---------------------------===// |
| 2 |
// |
| 3 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
// See https://llvm.org/LICENSE.txt for license information. |
| 5 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 |
// |
| 7 |
//===----------------------------------------------------------------------===// |
| 8 |
|
| 9 |
#include "NamespaceCommentCheck.h" |
| 10 |
#include "../utils/LexerUtils.h" |
| 11 |
#include "clang/AST/ASTContext.h" |
| 12 |
#include "clang/ASTMatchers/ASTMatchers.h" |
| 13 |
#include "clang/Basic/SourceLocation.h" |
| 14 |
#include "clang/Basic/TokenKinds.h" |
| 15 |
#include "clang/Lex/Lexer.h" |
| 16 |
#include "llvm/ADT/StringExtras.h" |
| 17 |
#include <optional> |
| 18 |
|
| 19 |
using namespace clang::ast_matchers; |
| 20 |
|
| 21 |
namespace clang::tidy::readability { |
| 22 |
|
| 23 |
NamespaceCommentCheck::NamespaceCommentCheck(StringRef Name, |
| 24 |
ClangTidyContext *Context) |
| 25 |
: ClangTidyCheck(Name, Context), |
| 26 |
NamespaceCommentPattern("^/[/*] *(end (of )?)? *(anonymous|unnamed)? *" |
| 27 |
"namespace( +([a-zA-Z0-9_:]+))?\\.? *(\\*/)?$", |
| 28 |
llvm::Regex::IgnoreCase), |
| 29 |
ShortNamespaceLines(Options.get("ShortNamespaceLines", 1u)), |
| 30 |
SpacesBeforeComments(Options.get("SpacesBeforeComments", 1u)) {} |
| 31 |
|
| 32 |
void NamespaceCommentCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { |
| 33 |
Options.store(Opts, "ShortNamespaceLines", ShortNamespaceLines); |
| 34 |
Options.store(Opts, "SpacesBeforeComments", SpacesBeforeComments); |
| 35 |
} |
| 36 |
|
| 37 |
void NamespaceCommentCheck::registerMatchers(MatchFinder *Finder) { |
| 38 |
Finder->addMatcher(namespaceDecl().bind("namespace"), this); |
| 39 |
} |
| 40 |
|
| 41 |
static bool locationsInSameFile(const SourceManager &Sources, |
| 42 |
SourceLocation Loc1, SourceLocation Loc2) { |
| 43 |
return Loc1.isFileID() && Loc2.isFileID() && |
| 44 |
Sources.getFileID(Loc1) == Sources.getFileID(Loc2); |
| 45 |
} |
| 46 |
|
| 47 |
static std::optional<std::string> |
| 48 |
getNamespaceNameAsWritten(SourceLocation &Loc, const SourceManager &Sources, |
| 49 |
const LangOptions &LangOpts) { |
| 50 |
// Loc should be at the begin of the namespace decl (usually, `namespace` |
| 51 |
// token). We skip the first token right away, but in case of `inline |
| 52 |
// namespace` or `namespace a::inline b` we can see both `inline` and |
| 53 |
// `namespace` keywords, which we just ignore. Nested parens/squares before |
| 54 |
// the opening brace can result from attributes. |
| 55 |
std::string Result; |
| 56 |
int Nesting = 0; |
| 57 |
while (std::optional<Token> T = utils::lexer::findNextTokenSkippingComments( |
| 58 |
Loc, Sources, LangOpts)) { |
| 59 |
Loc = T->getLocation(); |
| 60 |
if (T->is(tok::l_brace)) |
| 61 |
break; |
| 62 |
|
| 63 |
if (T->isOneOf(tok::l_square, tok::l_paren)) { |
| 64 |
++Nesting; |
| 65 |
} else if (T->isOneOf(tok::r_square, tok::r_paren)) { |
| 66 |
--Nesting; |
| 67 |
} else if (Nesting == 0) { |
| 68 |
if (T->is(tok::raw_identifier)) { |
| 69 |
StringRef ID = T->getRawIdentifier(); |
| 70 |
if (ID != "namespace" && ID != "inline") |
| 71 |
Result.append(std::string(ID)); |
| 72 |
} else if (T->is(tok::coloncolon)) { |
| 73 |
Result.append("::"); |
| 74 |
} else { // Any other kind of token is unexpected here. |
| 75 |
return std::nullopt; |
| 76 |
} |
| 77 |
} |
| 78 |
} |
| 79 |
return Result; |
| 80 |
} |
| 81 |
|
| 82 |
void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) { |
| 83 |
const auto *ND = Result.Nodes.getNodeAs<NamespaceDecl>("namespace"); |
| 84 |
const SourceManager &Sources = *Result.SourceManager; |
| 85 |
|
| 86 |
// Ignore namespaces inside macros and namespaces split across files. |
| 87 |
if (ND->getBeginLoc().isMacroID() || |
| 88 |
!locationsInSameFile(Sources, ND->getBeginLoc(), ND->getRBraceLoc())) |
| 89 |
return; |
| 90 |
|
| 91 |
// Don't require closing comments for namespaces spanning less than certain |
| 92 |
// number of lines. |
| 93 |
unsigned StartLine = Sources.getSpellingLineNumber(ND->getBeginLoc()); |
| 94 |
unsigned EndLine = Sources.getSpellingLineNumber(ND->getRBraceLoc()); |
| 95 |
if (EndLine - StartLine + 1 <= ShortNamespaceLines) |
| 96 |
return; |
| 97 |
|
| 98 |
// Find next token after the namespace closing brace. |
| 99 |
SourceLocation AfterRBrace = Lexer::getLocForEndOfToken( |
| 100 |
ND->getRBraceLoc(), /*Offset=*/0, Sources, getLangOpts()); |
| 101 |
SourceLocation Loc = AfterRBrace; |
| 102 |
SourceLocation LBraceLoc = ND->getBeginLoc(); |
| 103 |
|
| 104 |
// Currently for nested namespace (n1::n2::...) the AST matcher will match foo |
| 105 |
// then bar instead of a single match. So if we got a nested namespace we have |
| 106 |
// to skip the next ones. |
| 107 |
for (const auto &EndOfNameLocation : Ends) { |
| 108 |
if (Sources.isBeforeInTranslationUnit(ND->getLocation(), EndOfNameLocation)) |
| 109 |
return; |
| 110 |
} |
| 111 |
|
| 112 |
std::optional<std::string> NamespaceNameAsWritten = |
| 113 |
getNamespaceNameAsWritten(LBraceLoc, Sources, getLangOpts()); |
| 114 |
if (!NamespaceNameAsWritten) |
| 115 |
return; |
| 116 |
|
| 117 |
if (NamespaceNameAsWritten->empty() != ND->isAnonymousNamespace()) { |
| 118 |
// Apparently, we didn't find the correct namespace name. Give up. |
| 119 |
return; |
| 120 |
} |
| 121 |
|
| 122 |
Ends.push_back(LBraceLoc); |
| 123 |
|
| 124 |
Token Tok; |
| 125 |
// Skip whitespace until we find the next token. |
| 126 |
while (Lexer::getRawToken(Loc, Tok, Sources, getLangOpts()) || |
| 127 |
Tok.is(tok::semi)) { |
| 128 |
Loc = Loc.getLocWithOffset(1); |
| 129 |
} |
| 130 |
|
| 131 |
if (!locationsInSameFile(Sources, ND->getRBraceLoc(), Loc)) |
| 132 |
return; |
| 133 |
|
| 134 |
bool NextTokenIsOnSameLine = Sources.getSpellingLineNumber(Loc) == EndLine; |
| 135 |
// If we insert a line comment before the token in the same line, we need |
| 136 |
// to insert a line break. |
| 137 |
bool NeedLineBreak = NextTokenIsOnSameLine && Tok.isNot(tok::eof); |
| 138 |
|
| 139 |
SourceRange OldCommentRange(AfterRBrace, AfterRBrace); |
| 140 |
std::string Message = "%0 not terminated with a closing comment"; |
| 141 |
|
| 142 |
// Try to find existing namespace closing comment on the same line. |
| 143 |
if (Tok.is(tok::comment) && NextTokenIsOnSameLine) { |
| 144 |
StringRef Comment(Sources.getCharacterData(Loc), Tok.getLength()); |
| 145 |
SmallVector<StringRef, 7> Groups; |
| 146 |
if (NamespaceCommentPattern.match(Comment, &Groups)) { |
| 147 |
StringRef NamespaceNameInComment = Groups.size() > 5 ? Groups[5] : ""; |
| 148 |
StringRef Anonymous = Groups.size() > 3 ? Groups[3] : ""; |
| 149 |
|
| 150 |
if ((ND->isAnonymousNamespace() && NamespaceNameInComment.empty()) || |
| 151 |
(*NamespaceNameAsWritten == NamespaceNameInComment && |
| 152 |
Anonymous.empty())) { |
| 153 |
// Check if the namespace in the comment is the same. |
| 154 |
// FIXME: Maybe we need a strict mode, where we always fix namespace |
| 155 |
// comments with different format. |
| 156 |
return; |
| 157 |
} |
| 158 |
|
| 159 |
// Otherwise we need to fix the comment. |
| 160 |
NeedLineBreak = Comment.startswith("/*"); |
| 161 |
OldCommentRange = |
| 162 |
SourceRange(AfterRBrace, Loc.getLocWithOffset(Tok.getLength())); |
| 163 |
Message = |
| 164 |
(llvm::Twine( |
| 165 |
"%0 ends with a comment that refers to a wrong namespace '") + |
| 166 |
NamespaceNameInComment + "'") |
| 167 |
.str(); |
| 168 |
} else if (Comment.startswith("//")) { |
| 169 |
// Assume that this is an unrecognized form of a namespace closing line |
| 170 |
// comment. Replace it. |
| 171 |
NeedLineBreak = false; |
| 172 |
OldCommentRange = |
| 173 |
SourceRange(AfterRBrace, Loc.getLocWithOffset(Tok.getLength())); |
| 174 |
Message = "%0 ends with an unrecognized comment"; |
| 175 |
} |
| 176 |
// If it's a block comment, just move it to the next line, as it can be |
| 177 |
// multi-line or there may be other tokens behind it. |
| 178 |
} |
| 179 |
|
| 180 |
std::string NamespaceNameForDiag = |
| 181 |
ND->isAnonymousNamespace() ? "anonymous namespace" |
| 182 |
: ("namespace '" + *NamespaceNameAsWritten + "'"); |
| 183 |
|
| 184 |
std::string Fix(SpacesBeforeComments, ' '); |
| 185 |
Fix.append("// namespace"); |
| 186 |
if (!ND->isAnonymousNamespace()) |
| 187 |
Fix.append(" ").append(*NamespaceNameAsWritten); |
| 188 |
if (NeedLineBreak) |
| 189 |
Fix.append("\n"); |
| 190 |
|
| 191 |
// Place diagnostic at an old comment, or closing brace if we did not have it. |
| 192 |
SourceLocation DiagLoc = |
| 193 |
OldCommentRange.getBegin() != OldCommentRange.getEnd() |
| 194 |
? OldCommentRange.getBegin() |
| 195 |
: ND->getRBraceLoc(); |
| 196 |
|
| 197 |
diag(DiagLoc, Message) << NamespaceNameForDiag |
| 198 |
<< FixItHint::CreateReplacement( |
| 199 |
CharSourceRange::getCharRange(OldCommentRange), |
| 200 |
Fix); |
| 201 |
diag(ND->getLocation(), "%0 starts here", DiagnosticIDs::Note) |
| 202 |
<< NamespaceNameForDiag; |
| 203 |
} |
| 204 |
|
| 205 |
} // namespace clang::tidy::readability |