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", 1u)) {} 30 31 void NamespaceCommentCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { 32 Options.store(Opts, "ShortNamespaceLines", ShortNamespaceLines); 33 Options.store(Opts, "SpacesBeforeComments", SpacesBeforeComments); 34 } 35 36 void NamespaceCommentCheck::registerMatchers(MatchFinder *Finder) { 37 Finder->addMatcher(namespaceDecl().bind("namespace"), this); 38 } 39 40 bool locationsInSameFile(const SourceManager &Sources, SourceLocation Loc1, 41 SourceLocation Loc2) { 42 return Loc1.isFileID() && Loc2.isFileID() && 43 Sources.getFileID(Loc1) == Sources.getFileID(Loc2); 44 } 45 46 std::string getNamespaceComment(const NamespaceDecl *ND, bool InsertLineBreak) { 47 std::string Fix = "// namespace"; 48 if (!ND->isAnonymousNamespace()) 49 Fix.append(" ").append(ND->getNameAsString()); 50 if (InsertLineBreak) 51 Fix.append("\n"); 52 return Fix; 53 } 54 55 void 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; 81 // If we insert a line comment before the token in the same line, we need 82 // to insert a line break. 83 bool NeedLineBreak = NextTokenIsOnSameLine && Tok.isNot(tok::eof); 84 85 SourceRange OldCommentRange(AfterRBrace, AfterRBrace); 86 std::string Message = "%0 not terminated with a closing comment"; 87 88 // Try to find existing namespace closing comment on the same line. 89 if (Tok.is(tok::comment) && NextTokenIsOnSameLine) { 90 StringRef Comment(Sources.getCharacterData(Loc), Tok.getLength()); 91 SmallVector<StringRef, 7> Groups; 92 if (NamespaceCommentPattern.match(Comment, &Groups)) { 93 StringRef NamespaceNameInComment = Groups.size() > 5 ? Groups[5] : ""; 94 StringRef Anonymous = Groups.size() > 3 ? Groups[3] : ""; 95 96 // Check if the namespace in the comment is the same. 97 if ((ND->isAnonymousNamespace() && NamespaceNameInComment.empty()) || 98 (ND->getNameAsString() == NamespaceNameInComment && 99 Anonymous.empty())) { 100 // FIXME: Maybe we need a strict mode, where we always fix namespace 101 // comments with different format. 102 return; 103 } 104 105 // Otherwise we need to fix the comment. 106 NeedLineBreak = Comment.startswith("/*"); 107 OldCommentRange = 108 SourceRange(AfterRBrace, Loc.getLocWithOffset(Tok.getLength())); 109 Message = 110 (llvm::Twine( 111 "%0 ends with a comment that refers to a wrong namespace '") + 112 NamespaceNameInComment + "'").str(); 113 } else if (Comment.startswith("//")) { 114 // Assume that this is an unrecognized form of a namespace closing line 115 // comment. Replace it. 116 NeedLineBreak = false; 117 OldCommentRange = 118 SourceRange(AfterRBrace, Loc.getLocWithOffset(Tok.getLength())); 119 Message = "%0 ends with an unrecognized comment"; 120 } 121 // If it's a block comment, just move it to the next line, as it can be 122 // multi-line or there may be other tokens behind it. 123 } 124 125 std::string NamespaceName = 126 ND->isAnonymousNamespace() 127 ? "anonymous namespace" 128 : ("namespace '" + ND->getNameAsString() + "'"); 129 130 diag(AfterRBrace, Message) 131 << NamespaceName 132 << FixItHint::CreateReplacement( 133 OldCommentRange, std::string(SpacesBeforeComments, ' ') + 134 getNamespaceComment(ND, NeedLineBreak)); 135 diag(ND->getLocation(), "%0 starts here", DiagnosticIDs::Note) 136 << NamespaceName; 137 } 138 139 } // namespace readability 140 } // namespace tidy 141 } // namespace clang 142