clang-tools 22.0.0git
AbseilMatcher.h
Go to the documentation of this file.
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-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ABSEIL_ABSEILMATCHER_H
10#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ABSEIL_ABSEILMATCHER_H
11
12#include "clang/AST/ASTContext.h"
13#include "clang/ASTMatchers/ASTMatchFinder.h"
14#include <algorithm>
15
17
18/// Matches AST nodes that were found within Abseil files.
19///
20/// Example matches Y but not X
21/// (matcher = cxxRecordDecl(isInAbseilFile())
22/// \code
23/// #include "absl/strings/internal-file.h"
24/// class X {};
25/// \endcode
26/// absl/strings/internal-file.h:
27/// \code
28/// class Y {};
29/// \endcode
30///
31/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>,
32/// Matcher<NestedNameSpecifierLoc>
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, where
45 // [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_matchers
63
64#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ABSEIL_ABSEILMATCHER_H
AST_POLYMORPHIC_MATCHER(isInAbseilFile, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc, NestedNameSpecifierLoc))
Matches AST nodes that were found within Abseil files.