1//===-- FindAllMacros.cpp - find all macros ---------------------*- C++ -*-===//
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 "FindAllMacros.h"
10#include "HeaderMapCollector.h"
11#include "PathConfig.h"
12#include "SymbolInfo.h"
13#include "clang/Basic/FileManager.h"
14#include "clang/Basic/IdentifierTable.h"
15#include "clang/Basic/SourceManager.h"
16#include "clang/Lex/MacroInfo.h"
17#include "clang/Lex/Token.h"
18#include "llvm/Support/Path.h"
19#include <optional>
20
21namespace clang {
22namespace find_all_symbols {
23
24std::optional<SymbolInfo>
25FindAllMacros::CreateMacroSymbol(const Token &MacroNameTok,
26 const MacroInfo *info) {
27 std::string FilePath =
28 getIncludePath(SM: *SM, Loc: info->getDefinitionLoc(), Collector);
29 if (FilePath.empty())
30 return std::nullopt;
31 return SymbolInfo(MacroNameTok.getIdentifierInfo()->getName(),
32 SymbolInfo::SymbolKind::Macro, FilePath, {});
33}
34
35void FindAllMacros::MacroDefined(const Token &MacroNameTok,
36 const MacroDirective *MD) {
37 if (auto Symbol = CreateMacroSymbol(MacroNameTok, info: MD->getMacroInfo()))
38 ++FileSymbols[*Symbol].Seen;
39}
40
41void FindAllMacros::MacroUsed(const Token &Name, const MacroDefinition &MD) {
42 if (!MD || !SM->isInMainFile(Loc: SM->getExpansionLoc(Loc: Name.getLocation())))
43 return;
44 if (auto Symbol = CreateMacroSymbol(MacroNameTok: Name, info: MD.getMacroInfo()))
45 ++FileSymbols[*Symbol].Used;
46}
47
48void FindAllMacros::MacroExpands(const Token &MacroNameTok,
49 const MacroDefinition &MD, SourceRange Range,
50 const MacroArgs *Args) {
51 MacroUsed(Name: MacroNameTok, MD);
52}
53
54void FindAllMacros::Ifdef(SourceLocation Loc, const Token &MacroNameTok,
55 const MacroDefinition &MD) {
56 MacroUsed(Name: MacroNameTok, MD);
57}
58
59void FindAllMacros::Ifndef(SourceLocation Loc, const Token &MacroNameTok,
60 const MacroDefinition &MD) {
61 MacroUsed(Name: MacroNameTok, MD);
62}
63
64void FindAllMacros::EndOfMainFile() {
65 Reporter->reportSymbols(
66 FileName: SM->getFileEntryRefForID(FID: SM->getMainFileID())->getName(), Symbols: FileSymbols);
67 FileSymbols.clear();
68}
69
70} // namespace find_all_symbols
71} // namespace clang
72

source code of clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.cpp