| 1 |
//===--- AvoidNonConstGlobalVariablesCheck.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 "AvoidNonConstGlobalVariablesCheck.h" |
| 10 |
#include "clang/AST/ASTContext.h" |
| 11 |
#include "clang/ASTMatchers/ASTMatchFinder.h" |
| 12 |
#include "clang/ASTMatchers/ASTMatchers.h" |
| 13 |
|
| 14 |
using namespace clang::ast_matchers; |
| 15 |
|
| 16 |
namespace clang::tidy::cppcoreguidelines { |
| 17 |
|
| 18 |
namespace { |
| 19 |
AST_MATCHER(VarDecl, isLocalVarDecl) { return Node.isLocalVarDecl(); } |
| 20 |
} // namespace |
| 21 |
|
| 22 |
void AvoidNonConstGlobalVariablesCheck::registerMatchers(MatchFinder *Finder) { |
| 23 |
auto GlobalVariable = varDecl( |
| 24 |
hasGlobalStorage(), |
| 25 |
unless(anyOf( |
| 26 |
isLocalVarDecl(), isConstexpr(), hasType(isConstQualified()), |
| 27 |
hasType(referenceType())))); // References can't be changed, only the |
| 28 |
// data they reference can be changed. |
| 29 |
|
| 30 |
auto GlobalReferenceToNonConst = |
| 31 |
varDecl(hasGlobalStorage(), hasType(referenceType()), |
| 32 |
unless(hasType(references(qualType(isConstQualified()))))); |
| 33 |
|
| 34 |
auto GlobalPointerToNonConst = |
| 35 |
varDecl(hasGlobalStorage(), |
| 36 |
hasType(pointerType(pointee(unless(isConstQualified()))))); |
| 37 |
|
| 38 |
Finder->addMatcher(GlobalVariable.bind("non-const_variable"), this); |
| 39 |
Finder->addMatcher(GlobalReferenceToNonConst.bind("indirection_to_non-const"), |
| 40 |
this); |
| 41 |
Finder->addMatcher(GlobalPointerToNonConst.bind("indirection_to_non-const"), |
| 42 |
this); |
| 43 |
} |
| 44 |
|
| 45 |
void AvoidNonConstGlobalVariablesCheck::check( |
| 46 |
const MatchFinder::MatchResult &Result) { |
| 47 |
|
| 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. |
| 55 |
} |
| 56 |
|
| 57 |
if (const auto *VD = |
| 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'") |
| 62 |
<< VD |
| 63 |
<< VD->getType()->isPointerType(); // FIXME: Add fix-it hint to Variable |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
} // namespace clang::tidy::cppcoreguidelines |