Debian Codegraph @

src/MacroUtils.h

raw
1 /*
2 SPDX-FileCopyrightText: 2016 Sergio Martins <[email protected]>
3
4 SPDX-License-Identifier: LGPL-2.0-or-later
5 */
6
7 #ifndef CLAZY_MACRO_UTILS_H
8 #define CLAZY_MACRO_UTILS_H
9
10 #include "clazy_stl.h"
11
12 #include <clang/AST/ASTContext.h>
13 #include <clang/Basic/SourceLocation.h>
14 #include <clang/Frontend/CompilerInstance.h>
15 #include <clang/Lex/Lexer.h>
16 #include <clang/Lex/PreprocessorOptions.h>
17
18 #include <vector>
19
20 namespace clang
21 {
22 class CompilerInstance;
23 class SourceLocation;
24 }
25
26 namespace clazy
27 {
28 /**
29 * Returns true is macroName was defined via compiler invocation argument.
30 * Like $ gcc -Dfoo main.cpp
31 */
32 inline bool isPredefined(const clang::PreprocessorOptions &ppOpts, const llvm::StringRef &macroName)
33 {
34 const auto &macros = ppOpts.Macros;
35
36 for (const auto &macro : macros) {
37 if (macro.first == macroName) {
38 return true;
39 }
40 }
41
42 return false;
43 }
44
45 /**
46 * Returns true if the source location loc is inside a macro named macroName.
47 */
48 inline bool isInMacro(const clang::ASTContext *context, clang::SourceLocation loc, const llvm::StringRef &macroName)
49 {
50 if (loc.isValid() && loc.isMacroID()) {
51 llvm::StringRef macro = clang::Lexer::getImmediateMacroName(loc, context->getSourceManager(), context->getLangOpts());
52 return macro == macroName;
53 }
54
55 return false;
56 }
57
58 /**
59 * Returns true if the source location loc is inside any of the specified macros.
60 */
61 inline bool isInAnyMacro(const clang::ASTContext *context, clang::SourceLocation loc, const std::vector<llvm::StringRef> &macroNames)
62 {
63 return std::ranges::any_of(macroNames, [context, loc](const llvm::StringRef &macroName) {
64 return isInMacro(context, loc, macroName);
65 });
66 }
67
68 }
69
70 #endif