xref: /llvm-project/clang/lib/Format/NamespaceEndCommentsFixer.cpp (revision 772eb24e00629faaae0244aa0d6d6204542c579b)
1 //===--- NamespaceEndCommentsFixer.cpp --------------------------*- C++ -*-===//
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 /// \file
10 /// This file implements NamespaceEndCommentsFixer, a TokenAnalyzer that
11 /// fixes namespace end comments.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "NamespaceEndCommentsFixer.h"
16 #include "llvm/Support/Debug.h"
17 #include "llvm/Support/Regex.h"
18 
19 #define DEBUG_TYPE "namespace-end-comments-fixer"
20 
21 namespace clang {
22 namespace format {
23 
24 namespace {
25 // The maximal number of unwrapped lines that a short namespace spans.
26 // Short namespaces don't need an end comment.
27 static const int kShortNamespaceMaxLines = 1;
28 
29 // Computes the name of a namespace given the namespace token.
30 // Returns "" for anonymous namespace.
31 std::string computeName(const FormatToken *NamespaceTok) {
32   assert(NamespaceTok &&
33          NamespaceTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
34          "expecting a namespace token");
35   std::string name = "";
36   const FormatToken *Tok = NamespaceTok->getNextNonComment();
37   if (NamespaceTok->is(TT_NamespaceMacro)) {
38     // Collects all the non-comment tokens between opening parenthesis
39     // and closing parenthesis or comma.
40     assert(Tok && Tok->is(tok::l_paren) && "expected an opening parenthesis");
41     Tok = Tok->getNextNonComment();
42     while (Tok && !Tok->isOneOf(tok::r_paren, tok::comma)) {
43       name += Tok->TokenText;
44       Tok = Tok->getNextNonComment();
45     }
46   } else {
47     // For `namespace [[foo]] A::B::inline C {` or
48     // `namespace MACRO1 MACRO2 A::B::inline C {`, returns "A::B::inline C".
49     // Peek for the first '::' (or '{') and then return all tokens from one
50     // token before that up until the '{'.
51     const FormatToken *FirstNSTok = Tok;
52     while (Tok && !Tok->is(tok::l_brace) && !Tok->is(tok::coloncolon)) {
53       FirstNSTok = Tok;
54       Tok = Tok->getNextNonComment();
55     }
56 
57     Tok = FirstNSTok;
58     while (Tok && !Tok->is(tok::l_brace)) {
59       name += Tok->TokenText;
60       if (Tok->is(tok::kw_inline))
61         name += " ";
62       Tok = Tok->getNextNonComment();
63     }
64   }
65   return name;
66 }
67 
68 std::string computeEndCommentText(StringRef NamespaceName, bool AddNewline,
69                                   const FormatToken *NamespaceTok,
70                                   unsigned SpacesToAdd) {
71   std::string text = "//";
72   text.append(SpacesToAdd, ' ');
73   text += NamespaceTok->TokenText;
74   if (NamespaceTok->is(TT_NamespaceMacro))
75     text += "(";
76   else if (!NamespaceName.empty())
77     text += ' ';
78   text += NamespaceName;
79   if (NamespaceTok->is(TT_NamespaceMacro))
80     text += ")";
81   if (AddNewline)
82     text += '\n';
83   return text;
84 }
85 
86 bool hasEndComment(const FormatToken *RBraceTok) {
87   return RBraceTok->Next && RBraceTok->Next->is(tok::comment);
88 }
89 
90 bool validEndComment(const FormatToken *RBraceTok, StringRef NamespaceName,
91                      const FormatToken *NamespaceTok) {
92   assert(hasEndComment(RBraceTok));
93   const FormatToken *Comment = RBraceTok->Next;
94 
95   // Matches a valid namespace end comment.
96   // Valid namespace end comments don't need to be edited.
97   static const llvm::Regex NamespaceCommentPattern =
98       llvm::Regex("^/[/*] *(end (of )?)? *(anonymous|unnamed)? *"
99                   "namespace( +([a-zA-Z0-9:_]+))?\\.? *(\\*/)?$",
100                   llvm::Regex::IgnoreCase);
101   static const llvm::Regex NamespaceMacroCommentPattern =
102       llvm::Regex("^/[/*] *(end (of )?)? *(anonymous|unnamed)? *"
103                   "([a-zA-Z0-9_]+)\\(([a-zA-Z0-9:_]*)\\)\\.? *(\\*/)?$",
104                   llvm::Regex::IgnoreCase);
105 
106   SmallVector<StringRef, 8> Groups;
107   if (NamespaceTok->is(TT_NamespaceMacro) &&
108       NamespaceMacroCommentPattern.match(Comment->TokenText, &Groups)) {
109     StringRef NamespaceTokenText = Groups.size() > 4 ? Groups[4] : "";
110     // The name of the macro must be used.
111     if (NamespaceTokenText != NamespaceTok->TokenText)
112       return false;
113   } else if (NamespaceTok->isNot(tok::kw_namespace) ||
114              !NamespaceCommentPattern.match(Comment->TokenText, &Groups)) {
115     // Comment does not match regex.
116     return false;
117   }
118   StringRef NamespaceNameInComment = Groups.size() > 5 ? Groups[5] : "";
119   // Anonymous namespace comments must not mention a namespace name.
120   if (NamespaceName.empty() && !NamespaceNameInComment.empty())
121     return false;
122   StringRef AnonymousInComment = Groups.size() > 3 ? Groups[3] : "";
123   // Named namespace comments must not mention anonymous namespace.
124   if (!NamespaceName.empty() && !AnonymousInComment.empty())
125     return false;
126   if (NamespaceNameInComment == NamespaceName)
127     return true;
128 
129   // Has namespace comment flowed onto the next line.
130   // } // namespace
131   //   // verylongnamespacenamethatdidnotfitonthepreviouscommentline
132   if (!(Comment->Next && Comment->Next->is(TT_LineComment)))
133     return false;
134 
135   static const llvm::Regex CommentPattern = llvm::Regex(
136       "^/[/*] *( +([a-zA-Z0-9:_]+))?\\.? *(\\*/)?$", llvm::Regex::IgnoreCase);
137 
138   // Pull out just the comment text.
139   if (!CommentPattern.match(Comment->Next->TokenText, &Groups)) {
140     return false;
141   }
142   NamespaceNameInComment = Groups.size() > 2 ? Groups[2] : "";
143 
144   return (NamespaceNameInComment == NamespaceName);
145 }
146 
147 void addEndComment(const FormatToken *RBraceTok, StringRef EndCommentText,
148                    const SourceManager &SourceMgr,
149                    tooling::Replacements *Fixes) {
150   auto EndLoc = RBraceTok->Tok.getEndLoc();
151   auto Range = CharSourceRange::getCharRange(EndLoc, EndLoc);
152   auto Err = Fixes->add(tooling::Replacement(SourceMgr, Range, EndCommentText));
153   if (Err) {
154     llvm::errs() << "Error while adding namespace end comment: "
155                  << llvm::toString(std::move(Err)) << "\n";
156   }
157 }
158 
159 void updateEndComment(const FormatToken *RBraceTok, StringRef EndCommentText,
160                       const SourceManager &SourceMgr,
161                       tooling::Replacements *Fixes) {
162   assert(hasEndComment(RBraceTok));
163   const FormatToken *Comment = RBraceTok->Next;
164   auto Range = CharSourceRange::getCharRange(Comment->getStartOfNonWhitespace(),
165                                              Comment->Tok.getEndLoc());
166   auto Err = Fixes->add(tooling::Replacement(SourceMgr, Range, EndCommentText));
167   if (Err) {
168     llvm::errs() << "Error while updating namespace end comment: "
169                  << llvm::toString(std::move(Err)) << "\n";
170   }
171 }
172 } // namespace
173 
174 const FormatToken *
175 getNamespaceToken(const AnnotatedLine *Line,
176                   const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
177   if (!Line->Affected || Line->InPPDirective || !Line->startsWith(tok::r_brace))
178     return nullptr;
179   size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
180   if (StartLineIndex == UnwrappedLine::kInvalidIndex)
181     return nullptr;
182   assert(StartLineIndex < AnnotatedLines.size());
183   const FormatToken *NamespaceTok = AnnotatedLines[StartLineIndex]->First;
184   if (NamespaceTok->is(tok::l_brace)) {
185     // "namespace" keyword can be on the line preceding '{', e.g. in styles
186     // where BraceWrapping.AfterNamespace is true.
187     if (StartLineIndex > 0)
188       NamespaceTok = AnnotatedLines[StartLineIndex - 1]->First;
189   }
190   return NamespaceTok->getNamespaceToken();
191 }
192 
193 StringRef
194 getNamespaceTokenText(const AnnotatedLine *Line,
195                       const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
196   const FormatToken *NamespaceTok = getNamespaceToken(Line, AnnotatedLines);
197   return NamespaceTok ? NamespaceTok->TokenText : StringRef();
198 }
199 
200 NamespaceEndCommentsFixer::NamespaceEndCommentsFixer(const Environment &Env,
201                                                      const FormatStyle &Style)
202     : TokenAnalyzer(Env, Style) {}
203 
204 std::pair<tooling::Replacements, unsigned> NamespaceEndCommentsFixer::analyze(
205     TokenAnnotator &Annotator, SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
206     FormatTokenLexer &Tokens) {
207   const SourceManager &SourceMgr = Env.getSourceManager();
208   AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
209   tooling::Replacements Fixes;
210 
211   // Spin through the lines and ensure we have balanced braces.
212   int Braces = 0;
213   for (size_t I = 0, E = AnnotatedLines.size(); I != E; ++I) {
214     FormatToken *Tok = AnnotatedLines[I]->First;
215     while (Tok) {
216       Braces += Tok->is(tok::l_brace) ? 1 : Tok->is(tok::r_brace) ? -1 : 0;
217       Tok = Tok->Next;
218     }
219   }
220   // Don't attempt to comment unbalanced braces or this can
221   // lead to comments being placed on the closing brace which isn't
222   // the matching brace of the namespace. (occurs during incomplete editing).
223   if (Braces != 0) {
224     return {Fixes, 0};
225   }
226 
227   std::string AllNamespaceNames = "";
228   size_t StartLineIndex = SIZE_MAX;
229   StringRef NamespaceTokenText;
230   unsigned int CompactedNamespacesCount = 0;
231   for (size_t I = 0, E = AnnotatedLines.size(); I != E; ++I) {
232     const AnnotatedLine *EndLine = AnnotatedLines[I];
233     const FormatToken *NamespaceTok =
234         getNamespaceToken(EndLine, AnnotatedLines);
235     if (!NamespaceTok)
236       continue;
237     FormatToken *RBraceTok = EndLine->First;
238     if (RBraceTok->Finalized)
239       continue;
240     RBraceTok->Finalized = true;
241     const FormatToken *EndCommentPrevTok = RBraceTok;
242     // Namespaces often end with '};'. In that case, attach namespace end
243     // comments to the semicolon tokens.
244     if (RBraceTok->Next && RBraceTok->Next->is(tok::semi)) {
245       EndCommentPrevTok = RBraceTok->Next;
246     }
247     if (StartLineIndex == SIZE_MAX)
248       StartLineIndex = EndLine->MatchingOpeningBlockLineIndex;
249     std::string NamespaceName = computeName(NamespaceTok);
250     if (Style.CompactNamespaces) {
251       if (CompactedNamespacesCount == 0)
252         NamespaceTokenText = NamespaceTok->TokenText;
253       if ((I + 1 < E) &&
254           NamespaceTokenText ==
255               getNamespaceTokenText(AnnotatedLines[I + 1], AnnotatedLines) &&
256           StartLineIndex - CompactedNamespacesCount - 1 ==
257               AnnotatedLines[I + 1]->MatchingOpeningBlockLineIndex &&
258           !AnnotatedLines[I + 1]->First->Finalized) {
259         if (hasEndComment(EndCommentPrevTok)) {
260           // remove end comment, it will be merged in next one
261           updateEndComment(EndCommentPrevTok, std::string(), SourceMgr, &Fixes);
262         }
263         CompactedNamespacesCount++;
264         AllNamespaceNames = "::" + NamespaceName + AllNamespaceNames;
265         continue;
266       }
267       NamespaceName += AllNamespaceNames;
268       CompactedNamespacesCount = 0;
269       AllNamespaceNames = std::string();
270     }
271     // The next token in the token stream after the place where the end comment
272     // token must be. This is either the next token on the current line or the
273     // first token on the next line.
274     const FormatToken *EndCommentNextTok = EndCommentPrevTok->Next;
275     if (EndCommentNextTok && EndCommentNextTok->is(tok::comment))
276       EndCommentNextTok = EndCommentNextTok->Next;
277     if (!EndCommentNextTok && I + 1 < E)
278       EndCommentNextTok = AnnotatedLines[I + 1]->First;
279     bool AddNewline = EndCommentNextTok &&
280                       EndCommentNextTok->NewlinesBefore == 0 &&
281                       EndCommentNextTok->isNot(tok::eof);
282     const std::string EndCommentText =
283         computeEndCommentText(NamespaceName, AddNewline, NamespaceTok,
284                               Style.SpacesInLineCommentPrefix.Minimum);
285     if (!hasEndComment(EndCommentPrevTok)) {
286       bool isShort = I - StartLineIndex <= kShortNamespaceMaxLines + 1;
287       if (!isShort)
288         addEndComment(EndCommentPrevTok, EndCommentText, SourceMgr, &Fixes);
289     } else if (!validEndComment(EndCommentPrevTok, NamespaceName,
290                                 NamespaceTok)) {
291       updateEndComment(EndCommentPrevTok, EndCommentText, SourceMgr, &Fixes);
292     }
293     StartLineIndex = SIZE_MAX;
294   }
295   return {Fixes, 0};
296 }
297 
298 } // namespace format
299 } // namespace clang
300