File indexing completed on 2024-04-28 16:57:51

0001 /*
0002     This file is part of the clazy static checker.
0003 
0004     Copyright (C) 2016 Sergio Martins <smartins@kde.org>
0005 
0006     This library is free software; you can redistribute it and/or
0007     modify it under the terms of the GNU Library General Public
0008     License as published by the Free Software Foundation; either
0009     version 2 of the License, or (at your option) any later version.
0010 
0011     This library is distributed in the hope that it will be useful,
0012     but WITHOUT ANY WARRANTY; without even the implied warranty of
0013     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
0014     Library General Public License for more details.
0015 
0016     You should have received a copy of the GNU Library General Public License
0017     along with this library; see the file COPYING.LIB.  If not, write to
0018     the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
0019     Boston, MA 02110-1301, USA.
0020 */
0021 
0022 #ifndef CLAZY_MACRO_UTILS_H
0023 #define CLAZY_MACRO_UTILS_H
0024 
0025 #include "clazy_stl.h"
0026 
0027 #include <clang/AST/ASTContext.h>
0028 #include <clang/Frontend/CompilerInstance.h>
0029 #include <clang/Lex/Lexer.h>
0030 #include <clang/Lex/PreprocessorOptions.h>
0031 #include <clang/Basic/SourceLocation.h>
0032 
0033 #include <vector>
0034 
0035 namespace clang {
0036 class CompilerInstance;
0037 class SourceLocation;
0038 }
0039 
0040 namespace clazy
0041 {
0042 
0043 /**
0044  * Returns true is macroName was defined via compiler invocation argument.
0045  * Like $ gcc -Dfoo main.cpp
0046  */
0047 inline bool isPredefined(const clang::PreprocessorOptions &ppOpts, const llvm::StringRef &macroName)
0048 {
0049     const auto &macros = ppOpts.Macros;
0050 
0051     for (const auto &macro : macros) {
0052         if (macro.first == macroName)
0053             return true;
0054     }
0055 
0056     return false;
0057 }
0058 
0059 /**
0060  * Returns true if the source location loc is inside a macro named macroName.
0061  */
0062 inline bool isInMacro(const clang::ASTContext *context, clang::SourceLocation loc, const llvm::StringRef &macroName)
0063 {
0064     if (loc.isValid() && loc.isMacroID()) {
0065         llvm::StringRef macro = clang::Lexer::getImmediateMacroName(loc, context->getSourceManager(), context->getLangOpts());
0066         return macro == macroName;
0067     }
0068 
0069     return false;
0070 }
0071 
0072 /**
0073  * Returns true if the source location loc is inside any of the specified macros.
0074  */
0075 inline bool isInAnyMacro(const clang::ASTContext *context, clang::SourceLocation loc, const std::vector<llvm::StringRef> &macroNames)
0076 {
0077     return clazy::any_of(macroNames, [context, loc](const llvm::StringRef &macroName) {
0078             return isInMacro(context, loc, macroName);
0079         });
0080 }
0081 
0082 }
0083 
0084 #endif