1//===--- StaticDefinitionInAnonymousNamespaceCheck.cpp - clang-tidy--------===//
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#include "StaticDefinitionInAnonymousNamespaceCheck.h"
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/Lex/Lexer.h"
13
14using namespace clang::ast_matchers;
15
16namespace clang::tidy::readability {
17
18void StaticDefinitionInAnonymousNamespaceCheck::registerMatchers(
19 MatchFinder *Finder) {
20 Finder->addMatcher(
21 NodeMatch: namedDecl(anyOf(functionDecl(isDefinition(), isStaticStorageClass()),
22 varDecl(isDefinition(), isStaticStorageClass())),
23 isInAnonymousNamespace())
24 .bind(ID: "static-def"),
25 Action: this);
26}
27
28void StaticDefinitionInAnonymousNamespaceCheck::check(
29 const MatchFinder::MatchResult &Result) {
30 const auto *Def = Result.Nodes.getNodeAs<NamedDecl>(ID: "static-def");
31 // Skips all static definitions defined in Macro.
32 if (Def->getLocation().isMacroID())
33 return;
34
35 // Skips all static definitions in function scope.
36 const DeclContext *DC = Def->getDeclContext();
37 if (DC->getDeclKind() != Decl::Namespace)
38 return;
39
40 auto Diag =
41 diag(Def->getLocation(), "%0 is a static definition in "
42 "anonymous namespace; static is redundant here")
43 << Def;
44 Token Tok;
45 SourceLocation Loc = Def->getSourceRange().getBegin();
46 while (Loc < Def->getSourceRange().getEnd() &&
47 !Lexer::getRawToken(Loc, Result&: Tok, SM: *Result.SourceManager, LangOpts: getLangOpts(),
48 IgnoreWhiteSpace: true)) {
49 SourceRange TokenRange(Tok.getLocation(), Tok.getEndLoc());
50 StringRef SourceText =
51 Lexer::getSourceText(Range: CharSourceRange::getTokenRange(R: TokenRange),
52 SM: *Result.SourceManager, LangOpts: getLangOpts());
53 if (SourceText == "static") {
54 Diag << FixItHint::CreateRemoval(RemoveRange: TokenRange);
55 break;
56 }
57 Loc = Tok.getEndLoc();
58 }
59}
60
61} // namespace clang::tidy::readability
62

source code of clang-tools-extra/clang-tidy/readability/StaticDefinitionInAnonymousNamespaceCheck.cpp