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