blob: 3464a98b0c43b4b597e3992aef8fb123b85a74fd [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 Kornienkobef51cd2014-05-19 16:39:08 +000026 "namespace( +([a-zA-Z0-9_]+))? *(\\*/)?$",
27 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) {
37 Finder->addMatcher(namespaceDecl().bind("namespace"), this);
38}
39
40bool locationsInSameFile(const SourceManager &Sources, SourceLocation Loc1,
41 SourceLocation Loc2) {
42 return Loc1.isFileID() && Loc2.isFileID() &&
43 Sources.getFileID(Loc1) == Sources.getFileID(Loc2);
44}
45
Alexander Kornienko33fc3db2014-09-22 10:41:39 +000046std::string getNamespaceComment(const NamespaceDecl *ND, bool InsertLineBreak) {
Alexander Kornienkobef51cd2014-05-19 16:39:08 +000047 std::string Fix = "// namespace";
48 if (!ND->isAnonymousNamespace())
Alexander Kornienko33fc3db2014-09-22 10:41:39 +000049 Fix.append(" ").append(ND->getNameAsString());
Alexander Kornienkobef51cd2014-05-19 16:39:08 +000050 if (InsertLineBreak)
51 Fix.append("\n");
52 return Fix;
53}
54
55void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) {
56 const NamespaceDecl *ND = Result.Nodes.getNodeAs<NamespaceDecl>("namespace");
57 const SourceManager &Sources = *Result.SourceManager;
58
59 if (!locationsInSameFile(Sources, ND->getLocStart(), ND->getRBraceLoc()))
60 return;
61
62 // Don't require closing comments for namespaces spanning less than certain
63 // number of lines.
64 unsigned StartLine = Sources.getSpellingLineNumber(ND->getLocStart());
65 unsigned EndLine = Sources.getSpellingLineNumber(ND->getRBraceLoc());
66 if (EndLine - StartLine + 1 <= ShortNamespaceLines)
67 return;
68
69 // Find next token after the namespace closing brace.
70 SourceLocation AfterRBrace = ND->getRBraceLoc().getLocWithOffset(1);
71 SourceLocation Loc = AfterRBrace;
72 Token Tok;
73 // Skip whitespace until we find the next token.
74 while (Lexer::getRawToken(Loc, Tok, Sources, Result.Context->getLangOpts())) {
75 Loc = Loc.getLocWithOffset(1);
76 }
77 if (!locationsInSameFile(Sources, ND->getRBraceLoc(), Loc))
78 return;
79
80 bool NextTokenIsOnSameLine = Sources.getSpellingLineNumber(Loc) == EndLine;
Alexander Kornienko16ff5c72014-05-19 17:46:28 +000081 // If we insert a line comment before the token in the same line, we need
82 // to insert a line break.
Alexander Kornienkobef51cd2014-05-19 16:39:08 +000083 bool NeedLineBreak = NextTokenIsOnSameLine && Tok.isNot(tok::eof);
84
85 // Try to find existing namespace closing comment on the same line.
86 if (Tok.is(tok::comment) && NextTokenIsOnSameLine) {
87 StringRef Comment(Sources.getCharacterData(Loc), Tok.getLength());
88 SmallVector<StringRef, 6> Groups;
89 if (NamespaceCommentPattern.match(Comment, &Groups)) {
90 StringRef NamespaceNameInComment = Groups.size() >= 6 ? Groups[5] : "";
91
92 // Check if the namespace in the comment is the same.
93 if ((ND->isAnonymousNamespace() && NamespaceNameInComment.empty()) ||
94 ND->getNameAsString() == NamespaceNameInComment) {
95 // FIXME: Maybe we need a strict mode, where we always fix namespace
96 // comments with different format.
97 return;
98 }
99
100 // Otherwise we need to fix the comment.
101 NeedLineBreak = Comment.startswith("/*");
102 CharSourceRange OldCommentRange = CharSourceRange::getCharRange(
103 SourceRange(Loc, Loc.getLocWithOffset(Tok.getLength())));
104 diag(Loc, "namespace closing comment refers to a wrong namespace '%0'")
105 << NamespaceNameInComment
106 << FixItHint::CreateReplacement(
Alexander Kornienko33fc3db2014-09-22 10:41:39 +0000107 OldCommentRange, getNamespaceComment(ND, NeedLineBreak));
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000108 return;
109 }
110
111 // This is not a recognized form of a namespace closing comment.
112 // Leave line comment on the same line. Move block comment to the next line,
113 // as it can be multi-line or there may be other tokens behind it.
114 if (Comment.startswith("//"))
115 NeedLineBreak = false;
116 }
117
118 diag(ND->getLocation(), "namespace not terminated with a closing comment")
Alexander Kornienko33fc3db2014-09-22 10:41:39 +0000119 << FixItHint::CreateInsertion(AfterRBrace,
120 std::string(SpacesBeforeComments, ' ') +
121 getNamespaceComment(ND, NeedLineBreak));
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000122}
123
Alexander Kornienko33fc3db2014-09-22 10:41:39 +0000124} // namespace readability
Alexander Kornienkobef51cd2014-05-19 16:39:08 +0000125} // namespace tidy
126} // namespace clang