blob: eb3d7c505b831e6991a8153108d1b9d46186586d [file] [log] [blame]
Alexander Kornienkobef51cd2014-05-19 16:39:08 +00001//===--- NamespaceCommentCheck.cpp - clang-tidy ---------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Alexander Kornienkobef51cd2014-05-19 16:39:08 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "NamespaceCommentCheck.h"
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchers.h"
Ilya Biryukovf81ee432019-07-17 15:22:14 +000012#include "clang/Basic/SourceLocation.h"
Alexander Kornienkobef51cd2014-05-19 16:39:08 +000013#include "clang/Lex/Lexer.h"
Alexander Kornienko6e0cbc82014-09-12 08:53:36 +000014#include "llvm/ADT/StringExtras.h"
Alexander Kornienkobef51cd2014-05-19 16:39:08 +000015
16using namespace clang::ast_matchers;
17
18namespace clang {
19namespace tidy {
Alexander Kornienko33fc3db2014-09-22 10:41:39 +000020namespace readability {
Alexander Kornienkobef51cd2014-05-19 16:39:08 +000021
Alexander Kornienko6e0cbc82014-09-12 08:53:36 +000022NamespaceCommentCheck::NamespaceCommentCheck(StringRef Name,
23 ClangTidyContext *Context)
24 : ClangTidyCheck(Name, Context),
25 NamespaceCommentPattern("^/[/*] *(end (of )?)? *(anonymous|unnamed)? *"
Alexander Kornienko5a65e672018-01-11 13:00:28 +000026 "namespace( +([a-zA-Z0-9_:]+))?\\.? *(\\*/)?$",
Alexander Kornienkobef51cd2014-05-19 16:39:08 +000027 llvm::Regex::IgnoreCase),
Alexander Kornienko6e0cbc82014-09-12 08:53:36 +000028 ShortNamespaceLines(Options.get("ShortNamespaceLines", 1u)),
Alexander Kornienko1efc4252014-10-16 11:27:57 +000029 SpacesBeforeComments(Options.get("SpacesBeforeComments", 1u)) {}
Alexander Kornienko6e0cbc82014-09-12 08:53:36 +000030
31void NamespaceCommentCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
32 Options.store(Opts, "ShortNamespaceLines", ShortNamespaceLines);
33 Options.store(Opts, "SpacesBeforeComments", SpacesBeforeComments);
34}
Alexander Kornienkobef51cd2014-05-19 16:39:08 +000035
36void NamespaceCommentCheck::registerMatchers(MatchFinder *Finder) {
Aaron Ballman1f1b0672015-09-02 16:05:21 +000037 // Only register the matchers for C++; the functionality currently does not
38 // provide any benefit to other languages, despite being benign.
39 if (getLangOpts().CPlusPlus)
40 Finder->addMatcher(namespaceDecl().bind("namespace"), this);
Alexander Kornienkobef51cd2014-05-19 16:39:08 +000041}
42
Benjamin Kramere7103712015-03-23 12:49:15 +000043static bool locationsInSameFile(const SourceManager &Sources,
44 SourceLocation Loc1, SourceLocation Loc2) {
Alexander Kornienkobef51cd2014-05-19 16:39:08 +000045 return Loc1.isFileID() && Loc2.isFileID() &&
46 Sources.getFileID(Loc1) == Sources.getFileID(Loc2);
47}
48
Benjamin Kramere7103712015-03-23 12:49:15 +000049static std::string getNamespaceComment(const NamespaceDecl *ND,
50 bool InsertLineBreak) {
Alexander Kornienkobef51cd2014-05-19 16:39:08 +000051 std::string Fix = "// namespace";
52 if (!ND->isAnonymousNamespace())
Alexander Kornienko33fc3db2014-09-22 10:41:39 +000053 Fix.append(" ").append(ND->getNameAsString());
Alexander Kornienkobef51cd2014-05-19 16:39:08 +000054 if (InsertLineBreak)
55 Fix.append("\n");
56 return Fix;
57}
58
Alexander Kornienko5a65e672018-01-11 13:00:28 +000059static std::string getNamespaceComment(const std::string &NameSpaceName,
60 bool InsertLineBreak) {
61 std::string Fix = "// namespace ";
62 Fix.append(NameSpaceName);
63 if (InsertLineBreak)
64 Fix.append("\n");
65 return Fix;
66}
67
Alexander Kornienkobef51cd2014-05-19 16:39:08 +000068void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) {
Piotr Padlewski08124b12016-12-14 15:29:23 +000069 const auto *ND = Result.Nodes.getNodeAs<NamespaceDecl>("namespace");
Alexander Kornienkobef51cd2014-05-19 16:39:08 +000070 const SourceManager &Sources = *Result.SourceManager;
71
Stephen Kelly43465bf2018-08-09 22:42:26 +000072 if (!locationsInSameFile(Sources, ND->getBeginLoc(), ND->getRBraceLoc()))
Alexander Kornienkobef51cd2014-05-19 16:39:08 +000073 return;
74
75 // Don't require closing comments for namespaces spanning less than certain
76 // number of lines.
Stephen Kelly43465bf2018-08-09 22:42:26 +000077 unsigned StartLine = Sources.getSpellingLineNumber(ND->getBeginLoc());
Alexander Kornienkobef51cd2014-05-19 16:39:08 +000078 unsigned EndLine = Sources.getSpellingLineNumber(ND->getRBraceLoc());
79 if (EndLine - StartLine + 1 <= ShortNamespaceLines)
80 return;
81
82 // Find next token after the namespace closing brace.
83 SourceLocation AfterRBrace = ND->getRBraceLoc().getLocWithOffset(1);
84 SourceLocation Loc = AfterRBrace;
85 Token Tok;
Alexander Kornienko5a65e672018-01-11 13:00:28 +000086 SourceLocation LBracketLocation = ND->getLocation();
87 SourceLocation NestedNamespaceBegin = LBracketLocation;
88
89 // Currently for nested namepsace (n1::n2::...) the AST matcher will match foo
90 // then bar instead of a single match. So if we got a nested namespace we have
91 // to skip the next ones.
92 for (const auto &EndOfNameLocation : Ends) {
93 if (Sources.isBeforeInTranslationUnit(NestedNamespaceBegin,
94 EndOfNameLocation))
95 return;
96 }
97
98 // Ignore macros
99 if (!ND->getLocation().isMacroID()) {
100 while (Lexer::getRawToken(LBracketLocation, Tok, Sources, getLangOpts()) ||
101 !Tok.is(tok::l_brace)) {
102 LBracketLocation = LBracketLocation.getLocWithOffset(1);
103 }
104 }
105
Artem Dergachev8c099ce2019-04-23 21:15:26 +0000106 // FIXME: This probably breaks on comments between the namespace and its '{'.
Alexander Kornienko5a65e672018-01-11 13:00:28 +0000107 auto TextRange =
108 Lexer::getAsCharRange(SourceRange(NestedNamespaceBegin, LBracketLocation),
109 Sources, getLangOpts());
110 StringRef NestedNamespaceName =
Artem Dergachev8c099ce2019-04-23 21:15:26 +0000111 Lexer::getSourceText(TextRange, Sources, getLangOpts())
112 .rtrim('{') // Drop the { itself.
113 .rtrim(); // Drop any whitespace before it.
Alexander Kornienko5a65e672018-01-11 13:00:28 +0000114 bool IsNested = NestedNamespaceName.contains(':');
115
116 if (IsNested)
117 Ends.push_back(LBracketLocation);
118 else
119 NestedNamespaceName = ND->getName();
120
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000121 // Skip whitespace until we find the next token.
Gabor Horvathafad84c2016-09-24 02:13:45 +0000122 while (Lexer::getRawToken(Loc, Tok, Sources, getLangOpts()) ||
Alexander Kornienko2a538302015-12-16 15:44:42 +0000123 Tok.is(tok::semi)) {
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000124 Loc = Loc.getLocWithOffset(1);
125 }
Alexander Kornienko5a65e672018-01-11 13:00:28 +0000126
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000127 if (!locationsInSameFile(Sources, ND->getRBraceLoc(), Loc))
128 return;
129
130 bool NextTokenIsOnSameLine = Sources.getSpellingLineNumber(Loc) == EndLine;
Alexander Kornienko16ff5c72014-05-19 17:46:28 +0000131 // If we insert a line comment before the token in the same line, we need
132 // to insert a line break.
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000133 bool NeedLineBreak = NextTokenIsOnSameLine && Tok.isNot(tok::eof);
134
Alexander Kornienkoda4ebb22015-03-05 14:56:11 +0000135 SourceRange OldCommentRange(AfterRBrace, AfterRBrace);
Daniel Jasper08201e32015-03-05 23:17:32 +0000136 std::string Message = "%0 not terminated with a closing comment";
Alexander Kornienkoda4ebb22015-03-05 14:56:11 +0000137
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000138 // Try to find existing namespace closing comment on the same line.
139 if (Tok.is(tok::comment) && NextTokenIsOnSameLine) {
140 StringRef Comment(Sources.getCharacterData(Loc), Tok.getLength());
Alexander Kornienko27f126b2014-10-16 15:11:54 +0000141 SmallVector<StringRef, 7> Groups;
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000142 if (NamespaceCommentPattern.match(Comment, &Groups)) {
Alexander Kornienko27f126b2014-10-16 15:11:54 +0000143 StringRef NamespaceNameInComment = Groups.size() > 5 ? Groups[5] : "";
144 StringRef Anonymous = Groups.size() > 3 ? Groups[3] : "";
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000145
Alexander Kornienko5a65e672018-01-11 13:00:28 +0000146 if (IsNested && NestedNamespaceName == NamespaceNameInComment) {
147 // C++17 nested namespace.
148 return;
149 } else if ((ND->isAnonymousNamespace() &&
150 NamespaceNameInComment.empty()) ||
151 (ND->getNameAsString() == NamespaceNameInComment &&
152 Anonymous.empty())) {
153 // Check if the namespace in the comment is the same.
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000154 // 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("/*");
Alexander Kornienkoda4ebb22015-03-05 14:56:11 +0000161 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 '") +
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000166 NamespaceNameInComment + "'")
167 .str();
Alexander Kornienkoda4ebb22015-03-05 14:56:11 +0000168 } else if (Comment.startswith("//")) {
169 // Assume that this is an unrecognized form of a namespace closing line
170 // comment. Replace it.
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000171 NeedLineBreak = false;
Alexander Kornienkoda4ebb22015-03-05 14:56:11 +0000172 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.
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000178 }
179
Alexander Kornienkob23eb5e2014-11-17 17:32:32 +0000180 std::string NamespaceName =
181 ND->isAnonymousNamespace()
182 ? "anonymous namespace"
Alexander Kornienko5a65e672018-01-11 13:00:28 +0000183 : ("namespace '" + NestedNamespaceName.str() + "'");
Alexander Kornienkob23eb5e2014-11-17 17:32:32 +0000184
Ilya Biryukovf81ee432019-07-17 15:22:14 +0000185 // Place diagnostic at an old comment, or closing brace if we did not have it.
186 SourceLocation DiagLoc =
187 OldCommentRange.getBegin() != OldCommentRange.getEnd()
188 ? OldCommentRange.getBegin()
189 : ND->getRBraceLoc();
190
191 diag(DiagLoc, Message)
Alexander Kornienko5a65e672018-01-11 13:00:28 +0000192 << NamespaceName
193 << FixItHint::CreateReplacement(
194 CharSourceRange::getCharRange(OldCommentRange),
195 std::string(SpacesBeforeComments, ' ') +
196 (IsNested
197 ? getNamespaceComment(NestedNamespaceName, NeedLineBreak)
198 : getNamespaceComment(ND, NeedLineBreak)));
Alexander Kornienkob23eb5e2014-11-17 17:32:32 +0000199 diag(ND->getLocation(), "%0 starts here", DiagnosticIDs::Note)
200 << NamespaceName;
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000201}
202
Alexander Kornienko33fc3db2014-09-22 10:41:39 +0000203} // namespace readability
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000204} // namespace tidy
205} // namespace clang