aboutsummaryrefslogtreecommitdiffstats
path: root/src/MacroUtils.h
blob: d531e6742270c5bb19f1e9550f6848f0b77b9721 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
   This file is part of the clazy static checker.

  Copyright (C) 2016 Sergio Martins <smartins@kde.org>

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public License
  along with this library; see the file COPYING.LIB.  If not, write to
  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  Boston, MA 02110-1301, USA.
*/

#ifndef CLAZY_MACRO_UTILS_H
#define CLAZY_MACRO_UTILS_H

#include "clazy_export.h"
#include "clazy_stl.h"

#include <clang/AST/ASTContext.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Lex/Lexer.h>
#include <clang/Lex/PreprocessorOptions.h>
#include <clang/Basic/SourceLocation.h>

#include <string>
#include <vector>

namespace clang {
class CompilerInstance;
class SourceLocation;
}

namespace MacroUtils
{

/**
 * Returns true is macroName was defined via compiler invocation argument.
 * Like $ gcc -Dfoo main.cpp
 */
inline bool isPredefined(const clang::PreprocessorOptions &ppOpts, const std::string &macroName)
{
    const auto &macros = ppOpts.Macros;

    for (const auto &macro : macros) {
        if (macro.first == macroName)
            return true;
    }

    return false;
}

/**
 * Returns true if the source location loc is inside a macro named macroName.
 */
inline bool isInMacro(const clang::ASTContext *context, clang::SourceLocation loc, const std::string &macroName)
{
    if (loc.isValid() && loc.isMacroID()) {
        auto macro = clang::Lexer::getImmediateMacroName(loc, context->getSourceManager(), context->getLangOpts());
        return macro == macroName;
    }

    return false;
}

/**
 * Returns true if the source location loc is inside any of the specified macros.
 */
inline bool isInAnyMacro(const clang::ASTContext *context, clang::SourceLocation loc, const std::vector<std::string> &macroNames)
{
    return clazy_std::any_of(macroNames, [context, loc](const std::string &macroName) {
        return isInMacro(context, loc, macroName);
    });
}

}

#endif