10#include "clang/ASTMatchers/ASTMatchFinder.h"
11#include "clang/ASTMatchers/ASTMatchers.h"
20 AllowInternalLinkage(Options.get(
"AllowInternalLinkage", false)) {}
23 auto NamespaceMatcher = AllowInternalLinkage
24 ? namespaceDecl(unless(isAnonymous()))
27 varDecl(hasGlobalStorage(),
28 hasDeclContext(anyOf(NamespaceMatcher, translationUnitDecl())));
30 auto GlobalVariable = varDecl(
32 AllowInternalLinkage ? varDecl(unless(isStaticStorageClass()))
35 isConstexpr(), hasType(isConstQualified()),
36 hasType(referenceType()))));
39 auto GlobalReferenceToNonConst =
40 varDecl(GlobalContext, hasType(referenceType()),
41 unless(hasType(references(qualType(isConstQualified())))));
43 auto GlobalPointerToNonConst = varDecl(
44 GlobalContext, hasType(pointerType(pointee(unless(isConstQualified())))));
46 Finder->addMatcher(GlobalVariable.bind(
"non-const_variable"),
this);
47 Finder->addMatcher(GlobalReferenceToNonConst.bind(
"indirection_to_non-const"),
49 Finder->addMatcher(GlobalPointerToNonConst.bind(
"indirection_to_non-const"),
54 const MatchFinder::MatchResult &Result) {
55 if (
const auto *Variable =
56 Result.Nodes.getNodeAs<VarDecl>(
"non-const_variable")) {
57 diag(Variable->getLocation(),
"variable %0 is non-const and globally "
58 "accessible, consider making it const")
65 Result.Nodes.getNodeAs<VarDecl>(
"indirection_to_non-const")) {
66 diag(VD->getLocation(),
67 "variable %0 provides global access to a non-const object; consider "
68 "making the %select{referenced|pointed-to}1 data 'const'")
70 << VD->getType()->isPointerType();
76 Options.
store(Opts,
"AllowInternalLinkage", AllowInternalLinkage);
llvm::SmallString< 256U > Name
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
AvoidNonConstGlobalVariablesCheck(StringRef Name, ClangTidyContext *Context)
llvm::StringMap< ClangTidyValue > OptionMap