blob: 229cc626eeef3faa619da305a1b1337af6aa22e6 [file] [log] [blame]
Alexander Kornienkobef51cd2014-05-19 16:39:08 +00001//===--- NamespaceCommentCheck.cpp - clang-tidy ---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "NamespaceCommentCheck.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchers.h"
13#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
106 auto TextRange =
107 Lexer::getAsCharRange(SourceRange(NestedNamespaceBegin, LBracketLocation),
108 Sources, getLangOpts());
109 StringRef NestedNamespaceName =
110 Lexer::getSourceText(TextRange, Sources, getLangOpts()).rtrim();
111 bool IsNested = NestedNamespaceName.contains(':');
112
113 if (IsNested)
114 Ends.push_back(LBracketLocation);
115 else
116 NestedNamespaceName = ND->getName();
117
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000118 // Skip whitespace until we find the next token.
Gabor Horvathafad84c2016-09-24 02:13:45 +0000119 while (Lexer::getRawToken(Loc, Tok, Sources, getLangOpts()) ||
Alexander Kornienko2a538302015-12-16 15:44:42 +0000120 Tok.is(tok::semi)) {
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000121 Loc = Loc.getLocWithOffset(1);
122 }
Alexander Kornienko5a65e672018-01-11 13:00:28 +0000123
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000124 if (!locationsInSameFile(Sources, ND->getRBraceLoc(), Loc))
125 return;
126
127 bool NextTokenIsOnSameLine = Sources.getSpellingLineNumber(Loc) == EndLine;
Alexander Kornienko16ff5c72014-05-19 17:46:28 +0000128 // If we insert a line comment before the token in the same line, we need
129 // to insert a line break.
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000130 bool NeedLineBreak = NextTokenIsOnSameLine && Tok.isNot(tok::eof);
131
Alexander Kornienkoda4ebb22015-03-05 14:56:11 +0000132 SourceRange OldCommentRange(AfterRBrace, AfterRBrace);
Daniel Jasper08201e32015-03-05 23:17:32 +0000133 std::string Message = "%0 not terminated with a closing comment";
Alexander Kornienkoda4ebb22015-03-05 14:56:11 +0000134
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000135 // Try to find existing namespace closing comment on the same line.
136 if (Tok.is(tok::comment) && NextTokenIsOnSameLine) {
137 StringRef Comment(Sources.getCharacterData(Loc), Tok.getLength());
Alexander Kornienko27f126b2014-10-16 15:11:54 +0000138 SmallVector<StringRef, 7> Groups;
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000139 if (NamespaceCommentPattern.match(Comment, &Groups)) {
Alexander Kornienko27f126b2014-10-16 15:11:54 +0000140 StringRef NamespaceNameInComment = Groups.size() > 5 ? Groups[5] : "";
141 StringRef Anonymous = Groups.size() > 3 ? Groups[3] : "";
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000142
Alexander Kornienko5a65e672018-01-11 13:00:28 +0000143 if (IsNested && NestedNamespaceName == NamespaceNameInComment) {
144 // C++17 nested namespace.
145 return;
146 } else if ((ND->isAnonymousNamespace() &&
147 NamespaceNameInComment.empty()) ||
148 (ND->getNameAsString() == NamespaceNameInComment &&
149 Anonymous.empty())) {
150 // Check if the namespace in the comment is the same.
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000151 // FIXME: Maybe we need a strict mode, where we always fix namespace
152 // comments with different format.
153 return;
154 }
155
156 // Otherwise we need to fix the comment.
157 NeedLineBreak = Comment.startswith("/*");
Alexander Kornienkoda4ebb22015-03-05 14:56:11 +0000158 OldCommentRange =
159 SourceRange(AfterRBrace, Loc.getLocWithOffset(Tok.getLength()));
160 Message =
161 (llvm::Twine(
162 "%0 ends with a comment that refers to a wrong namespace '") +
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000163 NamespaceNameInComment + "'")
164 .str();
Alexander Kornienkoda4ebb22015-03-05 14:56:11 +0000165 } else if (Comment.startswith("//")) {
166 // Assume that this is an unrecognized form of a namespace closing line
167 // comment. Replace it.
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000168 NeedLineBreak = false;
Alexander Kornienkoda4ebb22015-03-05 14:56:11 +0000169 OldCommentRange =
170 SourceRange(AfterRBrace, Loc.getLocWithOffset(Tok.getLength()));
171 Message = "%0 ends with an unrecognized comment";
172 }
173 // If it's a block comment, just move it to the next line, as it can be
174 // multi-line or there may be other tokens behind it.
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000175 }
176
Alexander Kornienkob23eb5e2014-11-17 17:32:32 +0000177 std::string NamespaceName =
178 ND->isAnonymousNamespace()
179 ? "anonymous namespace"
Alexander Kornienko5a65e672018-01-11 13:00:28 +0000180 : ("namespace '" + NestedNamespaceName.str() + "'");
Alexander Kornienkob23eb5e2014-11-17 17:32:32 +0000181
Alexander Kornienkoda4ebb22015-03-05 14:56:11 +0000182 diag(AfterRBrace, Message)
Alexander Kornienko5a65e672018-01-11 13:00:28 +0000183 << NamespaceName
184 << FixItHint::CreateReplacement(
185 CharSourceRange::getCharRange(OldCommentRange),
186 std::string(SpacesBeforeComments, ' ') +
187 (IsNested
188 ? getNamespaceComment(NestedNamespaceName, NeedLineBreak)
189 : getNamespaceComment(ND, NeedLineBreak)));
Alexander Kornienkob23eb5e2014-11-17 17:32:32 +0000190 diag(ND->getLocation(), "%0 starts here", DiagnosticIDs::Note)
191 << NamespaceName;
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000192}
193
Alexander Kornienko33fc3db2014-09-22 10:41:39 +0000194} // namespace readability
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000195} // namespace tidy
196} // namespace clang