10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/ASTMatchers/ASTMatchers.h"
20 varDecl(hasGlobalStorage(),
21 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl())));
23 auto GlobalVariable = varDecl(
26 isConstexpr(), hasType(isConstQualified()),
27 hasType(referenceType()))));
30 auto GlobalReferenceToNonConst =
31 varDecl(GlobalContext, hasType(referenceType()),
32 unless(hasType(references(qualType(isConstQualified())))));
34 auto GlobalPointerToNonConst = varDecl(
35 GlobalContext, hasType(pointerType(pointee(unless(isConstQualified())))));
37 Finder->addMatcher(GlobalVariable.bind(
"non-const_variable"),
this);
38 Finder->addMatcher(GlobalReferenceToNonConst.bind(
"indirection_to_non-const"),
40 Finder->addMatcher(GlobalPointerToNonConst.bind(
"indirection_to_non-const"),
45 const MatchFinder::MatchResult &Result) {
47 if (
const auto *Variable =
48 Result.Nodes.getNodeAs<VarDecl>(
"non-const_variable")) {
49 diag(Variable->getLocation(),
"variable %0 is non-const and globally "
50 "accessible, consider making it const")
57 Result.Nodes.getNodeAs<VarDecl>(
"indirection_to_non-const")) {
58 diag(VD->getLocation(),
59 "variable %0 provides global access to a non-const object; consider "
60 "making the %select{referenced|pointed-to}1 data 'const'")
62 << VD->getType()->isPointerType();
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
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.