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

Provided by KDAB

Privacy Policy
Learn to use CMake with our Intro Training
Find out more

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