1 //===--- AvoidNonConstGlobalVariablesCheck.cpp - clang-tidy ---------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "AvoidNonConstGlobalVariablesCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/ASTMatchers/ASTMatchers.h"
14 using namespace clang::ast_matchers
;
16 namespace clang::tidy::cppcoreguidelines
{
19 AST_MATCHER(VarDecl
, isLocalVarDecl
) { return Node
.isLocalVarDecl(); }
22 void AvoidNonConstGlobalVariablesCheck::registerMatchers(MatchFinder
*Finder
) {
23 auto GlobalVariable
= varDecl(
26 isLocalVarDecl(), isConstexpr(), hasType(isConstQualified()),
27 hasType(referenceType())))); // References can't be changed, only the
28 // data they reference can be changed.
30 auto GlobalReferenceToNonConst
=
31 varDecl(hasGlobalStorage(), hasType(referenceType()),
32 unless(hasType(references(qualType(isConstQualified())))));
34 auto GlobalPointerToNonConst
=
35 varDecl(hasGlobalStorage(),
36 hasType(pointerType(pointee(unless(isConstQualified())))));
38 Finder
->addMatcher(GlobalVariable
.bind("non-const_variable"), this);
39 Finder
->addMatcher(GlobalReferenceToNonConst
.bind("indirection_to_non-const"),
41 Finder
->addMatcher(GlobalPointerToNonConst
.bind("indirection_to_non-const"),
45 void AvoidNonConstGlobalVariablesCheck::check(
46 const MatchFinder::MatchResult
&Result
) {
48 if (const auto *Variable
=
49 Result
.Nodes
.getNodeAs
<VarDecl
>("non-const_variable")) {
50 diag(Variable
->getLocation(), "variable %0 is non-const and globally "
51 "accessible, consider making it const")
52 << Variable
; // FIXME: Add fix-it hint to Variable
53 // Don't return early, a non-const variable may also be a pointer or
54 // reference to non-const data.
58 Result
.Nodes
.getNodeAs
<VarDecl
>("indirection_to_non-const")) {
59 diag(VD
->getLocation(),
60 "variable %0 provides global access to a non-const object; consider "
61 "making the %select{referenced|pointed-to}1 data 'const'")
63 << VD
->getType()->isPointerType(); // FIXME: Add fix-it hint to Variable
67 } // namespace clang::tidy::cppcoreguidelines