blob: ea369a769fb0fb4c9a7ba7abf1ec5851ebf08f48 [file] [log] [blame]
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +00001//===--- NamespaceEndCommentsFixer.cpp --------------------------*- C++ -*-===//
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/// \file
11/// \brief This file implements NamespaceEndCommentsFixer, a TokenAnalyzer that
12/// fixes namespace end comments.
13///
14//===----------------------------------------------------------------------===//
15
16#include "NamespaceEndCommentsFixer.h"
17#include "llvm/Support/Debug.h"
18#include "llvm/Support/Regex.h"
19
20#define DEBUG_TYPE "namespace-end-comments-fixer"
21
22namespace clang {
23namespace format {
24
25namespace {
Krasimir Georgiev9163fe22017-03-02 09:54:44 +000026// The maximal number of unwrapped lines that a short namespace spans.
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +000027// Short namespaces don't need an end comment.
28static const int kShortNamespaceMaxLines = 1;
29
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +000030// Computes the name of a namespace given the namespace token.
31// Returns "" for anonymous namespace.
32std::string computeName(const FormatToken *NamespaceTok) {
33 assert(NamespaceTok && NamespaceTok->is(tok::kw_namespace) &&
34 "expecting a namespace token");
35 std::string name = "";
36 // Collects all the non-comment tokens between 'namespace' and '{'.
37 const FormatToken *Tok = NamespaceTok->getNextNonComment();
38 while (Tok && !Tok->is(tok::l_brace)) {
39 name += Tok->TokenText;
40 Tok = Tok->getNextNonComment();
41 }
42 return name;
43}
44
45std::string computeEndCommentText(StringRef NamespaceName, bool AddNewline) {
46 std::string text = "// namespace";
47 if (!NamespaceName.empty()) {
48 text += ' ';
49 text += NamespaceName;
50 }
51 if (AddNewline)
52 text += '\n';
53 return text;
54}
55
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +000056bool hasEndComment(const FormatToken *RBraceTok) {
57 return RBraceTok->Next && RBraceTok->Next->is(tok::comment);
58}
59
60bool validEndComment(const FormatToken *RBraceTok, StringRef NamespaceName) {
61 assert(hasEndComment(RBraceTok));
62 const FormatToken *Comment = RBraceTok->Next;
Benjamin Kramer8ef820a2018-03-20 20:43:12 +000063
64 // Matches a valid namespace end comment.
65 // Valid namespace end comments don't need to be edited.
66 static llvm::Regex *const NamespaceCommentPattern =
67 new llvm::Regex("^/[/*] *(end (of )?)? *(anonymous|unnamed)? *"
68 "namespace( +([a-zA-Z0-9:_]+))?\\.? *(\\*/)?$",
69 llvm::Regex::IgnoreCase);
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +000070 SmallVector<StringRef, 7> Groups;
Benjamin Kramer8ef820a2018-03-20 20:43:12 +000071 if (NamespaceCommentPattern->match(Comment->TokenText, &Groups)) {
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +000072 StringRef NamespaceNameInComment = Groups.size() > 5 ? Groups[5] : "";
73 // Anonymous namespace comments must not mention a namespace name.
74 if (NamespaceName.empty() && !NamespaceNameInComment.empty())
75 return false;
76 StringRef AnonymousInComment = Groups.size() > 3 ? Groups[3] : "";
77 // Named namespace comments must not mention anonymous namespace.
78 if (!NamespaceName.empty() && !AnonymousInComment.empty())
79 return false;
80 return NamespaceNameInComment == NamespaceName;
81 }
82 return false;
83}
84
85void addEndComment(const FormatToken *RBraceTok, StringRef EndCommentText,
86 const SourceManager &SourceMgr,
87 tooling::Replacements *Fixes) {
88 auto EndLoc = RBraceTok->Tok.getEndLoc();
89 auto Range = CharSourceRange::getCharRange(EndLoc, EndLoc);
90 auto Err = Fixes->add(tooling::Replacement(SourceMgr, Range, EndCommentText));
91 if (Err) {
92 llvm::errs() << "Error while adding namespace end comment: "
93 << llvm::toString(std::move(Err)) << "\n";
94 }
95}
96
97void updateEndComment(const FormatToken *RBraceTok, StringRef EndCommentText,
98 const SourceManager &SourceMgr,
99 tooling::Replacements *Fixes) {
100 assert(hasEndComment(RBraceTok));
101 const FormatToken *Comment = RBraceTok->Next;
102 auto Range = CharSourceRange::getCharRange(Comment->getStartOfNonWhitespace(),
103 Comment->Tok.getEndLoc());
104 auto Err = Fixes->add(tooling::Replacement(SourceMgr, Range, EndCommentText));
105 if (Err) {
106 llvm::errs() << "Error while updating namespace end comment: "
107 << llvm::toString(std::move(Err)) << "\n";
108 }
109}
Krasimir Georgiev62103052018-04-19 13:02:15 +0000110} // namespace
Francois Ferrande56a8292017-06-14 12:29:47 +0000111
112const FormatToken *
Krasimir Georgiev6bbc7062018-04-23 10:02:59 +0000113getNamespaceToken(const AnnotatedLine *Line,
Francois Ferrande56a8292017-06-14 12:29:47 +0000114 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
Krasimir Georgiev6bbc7062018-04-23 10:02:59 +0000115 if (!Line->Affected || Line->InPPDirective || !Line->startsWith(tok::r_brace))
Francois Ferrande56a8292017-06-14 12:29:47 +0000116 return nullptr;
Krasimir Georgiev6bbc7062018-04-23 10:02:59 +0000117 size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
Francois Ferrande56a8292017-06-14 12:29:47 +0000118 if (StartLineIndex == UnwrappedLine::kInvalidIndex)
119 return nullptr;
120 assert(StartLineIndex < AnnotatedLines.size());
121 const FormatToken *NamespaceTok = AnnotatedLines[StartLineIndex]->First;
Marek Kurdejcaf6fd52017-09-27 07:51:51 +0000122 if (NamespaceTok->is(tok::l_brace)) {
123 // "namespace" keyword can be on the line preceding '{', e.g. in styles
124 // where BraceWrapping.AfterNamespace is true.
125 if (StartLineIndex > 0)
126 NamespaceTok = AnnotatedLines[StartLineIndex - 1]->First;
127 }
Francois Ferrande56a8292017-06-14 12:29:47 +0000128 // Detect "(inline)? namespace" in the beginning of a line.
129 if (NamespaceTok->is(tok::kw_inline))
130 NamespaceTok = NamespaceTok->getNextNonComment();
131 if (!NamespaceTok || NamespaceTok->isNot(tok::kw_namespace))
132 return nullptr;
133 return NamespaceTok;
134}
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +0000135
136NamespaceEndCommentsFixer::NamespaceEndCommentsFixer(const Environment &Env,
137 const FormatStyle &Style)
138 : TokenAnalyzer(Env, Style) {}
139
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000140std::pair<tooling::Replacements, unsigned> NamespaceEndCommentsFixer::analyze(
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +0000141 TokenAnnotator &Annotator, SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
142 FormatTokenLexer &Tokens) {
143 const SourceManager &SourceMgr = Env.getSourceManager();
Manuel Klimek0dddcf72018-04-23 09:34:26 +0000144 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +0000145 tooling::Replacements Fixes;
Francois Ferrande56a8292017-06-14 12:29:47 +0000146 std::string AllNamespaceNames = "";
147 size_t StartLineIndex = SIZE_MAX;
148 unsigned int CompactedNamespacesCount = 0;
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +0000149 for (size_t I = 0, E = AnnotatedLines.size(); I != E; ++I) {
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +0000150 const AnnotatedLine *EndLine = AnnotatedLines[I];
Francois Ferrande56a8292017-06-14 12:29:47 +0000151 const FormatToken *NamespaceTok =
152 getNamespaceToken(EndLine, AnnotatedLines);
153 if (!NamespaceTok)
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +0000154 continue;
Krasimir Georgievbda77392017-03-06 16:44:45 +0000155 FormatToken *RBraceTok = EndLine->First;
156 if (RBraceTok->Finalized)
157 continue;
158 RBraceTok->Finalized = true;
Krasimir Georgieveb62118e2017-03-07 14:07:43 +0000159 const FormatToken *EndCommentPrevTok = RBraceTok;
160 // Namespaces often end with '};'. In that case, attach namespace end
161 // comments to the semicolon tokens.
162 if (RBraceTok->Next && RBraceTok->Next->is(tok::semi)) {
163 EndCommentPrevTok = RBraceTok->Next;
164 }
Francois Ferrande56a8292017-06-14 12:29:47 +0000165 if (StartLineIndex == SIZE_MAX)
166 StartLineIndex = EndLine->MatchingOpeningBlockLineIndex;
167 std::string NamespaceName = computeName(NamespaceTok);
168 if (Style.CompactNamespaces) {
169 if ((I + 1 < E) &&
170 getNamespaceToken(AnnotatedLines[I + 1], AnnotatedLines) &&
171 StartLineIndex - CompactedNamespacesCount - 1 ==
172 AnnotatedLines[I + 1]->MatchingOpeningBlockLineIndex &&
173 !AnnotatedLines[I + 1]->First->Finalized) {
174 if (hasEndComment(EndCommentPrevTok)) {
175 // remove end comment, it will be merged in next one
176 updateEndComment(EndCommentPrevTok, std::string(), SourceMgr, &Fixes);
177 }
178 CompactedNamespacesCount++;
179 AllNamespaceNames = "::" + NamespaceName + AllNamespaceNames;
180 continue;
181 }
Krasimir Georgiev3d4c8122017-06-27 14:07:45 +0000182 NamespaceName += AllNamespaceNames;
Francois Ferrande56a8292017-06-14 12:29:47 +0000183 CompactedNamespacesCount = 0;
184 AllNamespaceNames = std::string();
185 }
Krasimir Georgieveb62118e2017-03-07 14:07:43 +0000186 // The next token in the token stream after the place where the end comment
187 // token must be. This is either the next token on the current line or the
188 // first token on the next line.
189 const FormatToken *EndCommentNextTok = EndCommentPrevTok->Next;
190 if (EndCommentNextTok && EndCommentNextTok->is(tok::comment))
191 EndCommentNextTok = EndCommentNextTok->Next;
192 if (!EndCommentNextTok && I + 1 < E)
193 EndCommentNextTok = AnnotatedLines[I + 1]->First;
194 bool AddNewline = EndCommentNextTok &&
195 EndCommentNextTok->NewlinesBefore == 0 &&
196 EndCommentNextTok->isNot(tok::eof);
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +0000197 const std::string EndCommentText =
198 computeEndCommentText(NamespaceName, AddNewline);
Krasimir Georgieveb62118e2017-03-07 14:07:43 +0000199 if (!hasEndComment(EndCommentPrevTok)) {
Krasimir Georgiev9163fe22017-03-02 09:54:44 +0000200 bool isShort = I - StartLineIndex <= kShortNamespaceMaxLines + 1;
201 if (!isShort)
Krasimir Georgieveb62118e2017-03-07 14:07:43 +0000202 addEndComment(EndCommentPrevTok, EndCommentText, SourceMgr, &Fixes);
Francois Ferrande56a8292017-06-14 12:29:47 +0000203 } else if (!validEndComment(EndCommentPrevTok, NamespaceName)) {
Krasimir Georgieveb62118e2017-03-07 14:07:43 +0000204 updateEndComment(EndCommentPrevTok, EndCommentText, SourceMgr, &Fixes);
Francois Ferrande56a8292017-06-14 12:29:47 +0000205 }
206 StartLineIndex = SIZE_MAX;
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +0000207 }
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000208 return {Fixes, 0};
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +0000209}
210
211} // namespace format
212} // namespace clang