1 //===--- 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"
14 #include "llvm/ADT/StringExtras.h"
15 
16 using namespace clang::ast_matchers;
17 
18 namespace clang {
19 namespace tidy {
20 namespace readability {
21 
22 NamespaceCommentCheck::NamespaceCommentCheck(StringRef Name,
23                                              ClangTidyContext *Context)
24     : ClangTidyCheck(Name, Context),
25       NamespaceCommentPattern("^/[/*] *(end (of )?)? *(anonymous|unnamed)? *"
26                               "namespace( +([a-zA-Z0-9_]+))? *(\\*/)?$",
27                               llvm::Regex::IgnoreCase),
28       ShortNamespaceLines(Options.get("ShortNamespaceLines", 1u)),
29       SpacesBeforeComments(Options.get("SpacesBeforeComments",
30                                        Name.startswith("google") ? 2u : 1u)) {}
31 
32 void NamespaceCommentCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
33   Options.store(Opts, "ShortNamespaceLines", ShortNamespaceLines);
34   Options.store(Opts, "SpacesBeforeComments", SpacesBeforeComments);
35 }
36 
37 void NamespaceCommentCheck::registerMatchers(MatchFinder *Finder) {
38   Finder->addMatcher(namespaceDecl().bind("namespace"), this);
39 }
40 
41 bool locationsInSameFile(const SourceManager &Sources, SourceLocation Loc1,
42                          SourceLocation Loc2) {
43   return Loc1.isFileID() && Loc2.isFileID() &&
44          Sources.getFileID(Loc1) == Sources.getFileID(Loc2);
45 }
46 
47 std::string getNamespaceComment(const NamespaceDecl *ND, bool InsertLineBreak) {
48   std::string Fix = "// namespace";
49   if (!ND->isAnonymousNamespace())
50     Fix.append(" ").append(ND->getNameAsString());
51   if (InsertLineBreak)
52     Fix.append("\n");
53   return Fix;
54 }
55 
56 void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) {
57   const NamespaceDecl *ND = Result.Nodes.getNodeAs<NamespaceDecl>("namespace");
58   const SourceManager &Sources = *Result.SourceManager;
59 
60   if (!locationsInSameFile(Sources, ND->getLocStart(), ND->getRBraceLoc()))
61     return;
62 
63   // Don't require closing comments for namespaces spanning less than certain
64   // number of lines.
65   unsigned StartLine = Sources.getSpellingLineNumber(ND->getLocStart());
66   unsigned EndLine = Sources.getSpellingLineNumber(ND->getRBraceLoc());
67   if (EndLine - StartLine + 1 <= ShortNamespaceLines)
68     return;
69 
70   // Find next token after the namespace closing brace.
71   SourceLocation AfterRBrace = ND->getRBraceLoc().getLocWithOffset(1);
72   SourceLocation Loc = AfterRBrace;
73   Token Tok;
74   // Skip whitespace until we find the next token.
75   while (Lexer::getRawToken(Loc, Tok, Sources, Result.Context->getLangOpts())) {
76     Loc = Loc.getLocWithOffset(1);
77   }
78   if (!locationsInSameFile(Sources, ND->getRBraceLoc(), Loc))
79     return;
80 
81   bool NextTokenIsOnSameLine = Sources.getSpellingLineNumber(Loc) == EndLine;
82   // If we insert a line comment before the token in the same line, we need
83   // to insert a line break.
84   bool NeedLineBreak = NextTokenIsOnSameLine && Tok.isNot(tok::eof);
85 
86   // Try to find existing namespace closing comment on the same line.
87   if (Tok.is(tok::comment) && NextTokenIsOnSameLine) {
88     StringRef Comment(Sources.getCharacterData(Loc), Tok.getLength());
89     SmallVector<StringRef, 6> Groups;
90     if (NamespaceCommentPattern.match(Comment, &Groups)) {
91       StringRef NamespaceNameInComment = Groups.size() >= 6 ? Groups[5] : "";
92 
93       // Check if the namespace in the comment is the same.
94       if ((ND->isAnonymousNamespace() && NamespaceNameInComment.empty()) ||
95           ND->getNameAsString() == NamespaceNameInComment) {
96         // FIXME: Maybe we need a strict mode, where we always fix namespace
97         // comments with different format.
98         return;
99       }
100 
101       // Otherwise we need to fix the comment.
102       NeedLineBreak = Comment.startswith("/*");
103       CharSourceRange OldCommentRange = CharSourceRange::getCharRange(
104           SourceRange(Loc, Loc.getLocWithOffset(Tok.getLength())));
105       diag(Loc, "namespace closing comment refers to a wrong namespace '%0'")
106           << NamespaceNameInComment
107           << FixItHint::CreateReplacement(
108                  OldCommentRange, getNamespaceComment(ND, NeedLineBreak));
109       return;
110     }
111 
112     // This is not a recognized form of a namespace closing comment.
113     // Leave line comment on the same line. Move block comment to the next line,
114     // as it can be multi-line or there may be other tokens behind it.
115     if (Comment.startswith("//"))
116       NeedLineBreak = false;
117   }
118 
119   diag(ND->getLocation(), "namespace not terminated with a closing comment")
120       << FixItHint::CreateInsertion(AfterRBrace,
121                                     std::string(SpacesBeforeComments, ' ') +
122                                         getNamespaceComment(ND, NeedLineBreak));
123 }
124 
125 } // namespace readability
126 } // namespace tidy
127 } // namespace clang
128