|
| 1 | +//===--- MarkStaticCheck.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 "MarkStaticCheck.h" |
| 10 | +#include "clang/AST/Decl.h" |
| 11 | +#include "clang/ASTMatchers/ASTMatchFinder.h" |
| 12 | +#include "clang/ASTMatchers/ASTMatchers.h" |
| 13 | +#include "clang/ASTMatchers/ASTMatchersMacros.h" |
| 14 | +#include "clang/Basic/Specifiers.h" |
| 15 | + |
| 16 | +using namespace clang::ast_matchers; |
| 17 | + |
| 18 | +namespace clang::tidy::readability { |
| 19 | + |
| 20 | +namespace { |
| 21 | + |
| 22 | +AST_POLYMORPHIC_MATCHER(isFirstDecl, |
| 23 | + AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, |
| 24 | + VarDecl)) { |
| 25 | + return Node.isFirstDecl(); |
| 26 | +} |
| 27 | + |
| 28 | +AST_MATCHER(Decl, isInMainFile) { |
| 29 | + return Finder->getASTContext().getSourceManager().isInMainFile( |
| 30 | + Node.getLocation()); |
| 31 | +} |
| 32 | + |
| 33 | +AST_POLYMORPHIC_MATCHER(isExternStorageClass, |
| 34 | + AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, |
| 35 | + VarDecl)) { |
| 36 | + return Node.getStorageClass() == SC_Extern; |
| 37 | +} |
| 38 | + |
| 39 | +} // namespace |
| 40 | + |
| 41 | +void MarkStaticCheck::registerMatchers(MatchFinder *Finder) { |
| 42 | + auto Common = |
| 43 | + allOf(isFirstDecl(), isInMainFile(), |
| 44 | + unless(anyOf(isStaticStorageClass(), isExternStorageClass(), |
| 45 | + isInAnonymousNamespace()))); |
| 46 | + Finder->addMatcher( |
| 47 | + functionDecl(Common, unless(cxxMethodDecl()), unless(isMain())) |
| 48 | + .bind("fn"), |
| 49 | + this); |
| 50 | + Finder->addMatcher(varDecl(Common, hasGlobalStorage()).bind("var"), this); |
| 51 | +} |
| 52 | + |
| 53 | +void MarkStaticCheck::check(const MatchFinder::MatchResult &Result) { |
| 54 | + if (const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("fn")) { |
| 55 | + diag(FD->getLocation(), "function %0 can be static") << FD; |
| 56 | + return; |
| 57 | + } |
| 58 | + if (const auto *VD = Result.Nodes.getNodeAs<VarDecl>("var")) { |
| 59 | + diag(VD->getLocation(), "variable %0 can be static") << VD; |
| 60 | + return; |
| 61 | + } |
| 62 | + llvm_unreachable(""); |
| 63 | +} |
| 64 | + |
| 65 | +} // namespace clang::tidy::readability |
0 commit comments