65 lines · c
1//===- AbseilMatcher.h - 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-exception6//7//===----------------------------------------------------------------------===//8 9#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ABSEIL_ABSEILMATCHER_H10#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ABSEIL_ABSEILMATCHER_H11 12#include "clang/AST/ASTContext.h"13#include "clang/ASTMatchers/ASTMatchFinder.h"14#include <algorithm>15 16namespace clang::ast_matchers {17 18/// Matches AST nodes that were found within Abseil files.19///20/// Example matches Y but not X21/// (matcher = cxxRecordDecl(isInAbseilFile())22/// \code23/// #include "absl/strings/internal-file.h"24/// class X {};25/// \endcode26/// absl/strings/internal-file.h:27/// \code28/// class Y {};29/// \endcode30///31/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>,32/// Matcher<NestedNameSpecifierLoc>33AST_POLYMORPHIC_MATCHER(34 isInAbseilFile, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc,35 NestedNameSpecifierLoc)) {36 auto &SourceManager = Finder->getASTContext().getSourceManager();37 const SourceLocation Loc = SourceManager.getSpellingLoc(Node.getBeginLoc());38 if (Loc.isInvalid())39 return false;40 OptionalFileEntryRef FileEntry =41 SourceManager.getFileEntryRefForID(SourceManager.getFileID(Loc));42 if (!FileEntry)43 return false;44 // Determine whether filepath contains "absl/[absl-library]" substring, where45 // [absl-library] is AbseilLibraries list entry.46 StringRef Path = FileEntry->getName();47 static constexpr llvm::StringLiteral AbslPrefix("absl/");48 const size_t PrefixPosition = Path.find(AbslPrefix);49 if (PrefixPosition == StringRef::npos)50 return false;51 Path = Path.drop_front(PrefixPosition + AbslPrefix.size());52 static constexpr llvm::StringLiteral AbseilLibraries[] = {53 "algorithm", "base", "container", "debugging", "flags",54 "hash", "iterator", "memory", "meta", "numeric",55 "profiling", "random", "status", "strings", "synchronization",56 "time", "types", "utility"};57 return llvm::any_of(AbseilLibraries, [&](llvm::StringLiteral Library) {58 return Path.starts_with(Library);59 });60}61 62} // namespace clang::ast_matchers63 64#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ABSEIL_ABSEILMATCHER_H65