summaryrefslogtreecommitdiff
path: root/compilerplugins/clang/compat.hxx
blob: 990f0ac78c26cb6d4b68afa45afc7739b5058197 (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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#ifndef INCLUDED_COMPILERPLUGINS_CLANG_COMPAT_HXX
#define INCLUDED_COMPILERPLUGINS_CLANG_COMPAT_HXX

#include <memory>
#include <string>

#include "clang/AST/Decl.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/Type.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticIDs.h"
#include "clang/Basic/Linkage.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Visibility.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/PPCallbacks.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/raw_ostream.h"

#include "config_clang.h"

// Compatibility wrapper to abstract over (trivial) changes in the Clang API:
namespace compat {

inline bool isLookupContext(clang::DeclContext const & ctxt) {
#if CLANG_VERSION >= 30700
    return ctxt.isLookupContext();
#else
    return !ctxt.isFunctionOrMethod()
        && ctxt.getDeclKind() != clang::Decl::LinkageSpec;
#endif
}

inline bool forallBases(
    clang::CXXRecordDecl const & decl,
    clang::CXXRecordDecl::ForallBasesCallback BaseMatches,
    void* callbackParam,
    bool AllowShortCircuit)
{
#if CLANG_VERSION >= 30800
    (void) callbackParam;
    return decl.forallBases(BaseMatches, AllowShortCircuit);
#else
    return decl.forallBases(BaseMatches, callbackParam, AllowShortCircuit);
#endif
}

inline clang::QualType getReturnType(clang::FunctionDecl const & decl) {
#if CLANG_VERSION >= 30500
    return decl.getReturnType();
#else
    return decl.getResultType();
#endif
}


#if CLANG_VERSION >= 30900
inline clang::ArrayRef<clang::ParmVarDecl *> parameters(
    clang::FunctionDecl const & decl)
{
    return decl.parameters();
}
#elif CLANG_VERSION >= 30500
inline clang::FunctionDecl::param_const_range parameters(
    clang::FunctionDecl const & decl)
{
    return decl.params();
}
#else
struct FunctionDeclParamsWrapper
{
    clang::FunctionDecl const & decl;
    FunctionDeclParamsWrapper(clang::FunctionDecl const & _decl) : decl(_decl) {}
    clang::FunctionDecl::param_const_iterator begin() const { return decl.param_begin(); }
    clang::FunctionDecl::param_const_iterator end() const { return decl.param_end(); }
};
inline FunctionDeclParamsWrapper parameters(
    clang::FunctionDecl const & decl)
{
    return FunctionDeclParamsWrapper(decl);
}
#endif


inline clang::QualType getReturnType(clang::FunctionProtoType const & type) {
#if CLANG_VERSION >= 30500
    return type.getReturnType();
#else
    return type.getResultType();
#endif
}

inline unsigned getNumParams(clang::FunctionProtoType const & type) {
#if CLANG_VERSION >= 30500
    return type.getNumParams();
#else
    return type.getNumArgs();
#endif
}

inline clang::QualType getParamType(
    clang::FunctionProtoType const & type, unsigned i)
{
#if CLANG_VERSION >= 30500
    return type.getParamType(i);
#else
    return type.getArgType(i);
#endif
}

inline clang::Stmt::const_child_iterator begin(
    clang::Stmt::const_child_range const & range)
{
#if CLANG_VERSION >= 30800
    return range.begin();
#else
    return range.first;
#endif
}

inline clang::Stmt::const_child_iterator end(
    clang::Stmt::const_child_range const & range)
{
#if CLANG_VERSION >= 30800
    return range.end();
#else
    return range.second;
#endif
}

inline unsigned getBuiltinCallee(clang::CallExpr const & expr) {
#if CLANG_VERSION >= 30500
    return expr.getBuiltinCallee();
#else
    return expr.isBuiltinCall();
#endif
}

inline unsigned getCustomDiagID(
    clang::DiagnosticsEngine & engine, clang::DiagnosticsEngine::Level L,
    llvm::StringRef FormatString)
{
#if CLANG_VERSION >= 30500
    return engine.getDiagnosticIDs()->getCustomDiagID(
        static_cast<clang::DiagnosticIDs::Level>(L), FormatString);
#else
    return engine.getCustomDiagID(L, FormatString);
#endif
}

inline std::unique_ptr<llvm::raw_fd_ostream> create_raw_fd_ostream(
    char const * Filename, std::string & ErrorInfo)
{
#if CLANG_VERSION >= 30600
    std::error_code ec;
    std::unique_ptr<llvm::raw_fd_ostream> s(
        new llvm::raw_fd_ostream(Filename, ec, llvm::sys::fs::F_None));
    ErrorInfo = ec ? "error: " + ec.message() : std::string();
    return s;
#elif CLANG_VERSION >= 30500
    return std::unique_ptr<llvm::raw_fd_ostream>(
        new llvm::raw_fd_ostream(Filename, ErrorInfo, llvm::sys::fs::F_None));
#else
    return std::unique_ptr<llvm::raw_fd_ostream>(
        new llvm::raw_fd_ostream(Filename, ErrorInfo));
#endif
}

#if CLANG_VERSION >= 30700
using MacroDefinitionParam = clang::MacroDefinition const &;
#else
using MacroDefinitionParam = clang::MacroDirective const *;
#endif

inline void addPPCallbacks(
    clang::Preprocessor & preprocessor, clang::PPCallbacks * C)
{
#if CLANG_VERSION >= 30600
    preprocessor.addPPCallbacks(std::unique_ptr<clang::PPCallbacks>(C));
#else
    preprocessor.addPPCallbacks(C);
#endif
}

inline bool isMacroArgExpansion(
    clang::CompilerInstance& compiler, clang::SourceLocation location,
    clang::SourceLocation * startLocation)
{
#if CLANG_VERSION >= 30900
    return compiler.getSourceManager().isMacroArgExpansion(
        location, startLocation);
#else
    bool b = compiler.getSourceManager().isMacroArgExpansion(location);
    if (b) {
        *startLocation = compiler.getSourceManager()
            .getSLocEntry(compiler.getSourceManager().getFileID(location))
            .getExpansion().getExpansionLocStart();
    }
    return b;
#endif
}

inline llvm::StringRef getImmediateMacroNameForDiagnostics(
    clang::SourceLocation Loc, clang::SourceManager const & SM,
    clang::LangOptions const &LangOpts)
{
#if CLANG_VERSION >= 30900
    return clang::Lexer::getImmediateMacroNameForDiagnostics(Loc, SM, LangOpts);
#else
    using namespace clang;
    // Verbatim copy from Clang's lib/Lex/Lexer.cpp:

    assert(Loc.isMacroID() && "Only reasonable to call this on macros");
    // Walk past macro argument expansion.
    while (SM.isMacroArgExpansion(Loc))
        Loc = SM.getImmediateExpansionRange(Loc).first;

    // If the macro's spelling has no FileID, then it's actually a token paste
    // or stringization (or similar) and not a macro at all.
    if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
        return StringRef();

    // Find the spelling location of the start of the non-argument expansion
    // range. This is where the macro name was spelled in order to begin
    // expanding this macro.
    Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);

    // Dig out the buffer where the macro name was spelled and the extents of
    // the name so that we can render it into the expansion note.
    std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
    unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
    StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
    return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
#endif
}

inline auto getAsTagDecl(clang::Type const& t) -> clang::TagDecl *
{
#if CLANG_VERSION >= 30500
    // TODO not sure if it works with clang 3.6, trunk is known to work
    return t.getAsTagDecl();
#else
    return t.getAs<clang::TagType>()->getDecl();
#endif
}

inline bool isStdNamespace(clang::DeclContext const & context) {
#if CLANG_VERSION >= 30500
    return context.isStdNamespace();
#else
    // cf. lib/AST/DeclBase.cpp:
    if (!context.isNamespace()) {
        return false;
    }
    const clang::NamespaceDecl *ND = clang::cast<clang::NamespaceDecl>(
        &context);
    if (ND->isInline()) {
        return isStdNamespace(*ND->getParent());
    }
    if (!context.getParent()->getRedeclContext()->isTranslationUnit()) {
        return false;
    }
    const clang::IdentifierInfo *II = ND->getIdentifier();
    return II && II->isStr("std");
#endif
}

// Work around <http://reviews.llvm.org/D22128>:
//
// SfxErrorHandler::GetClassString (svtools/source/misc/ehdl.cxx):
//
//   ErrorResource_Impl aEr(aId, (sal_uInt16)lClassId);
//   if(aEr)
//   {
//       rStr = static_cast<ResString>(aEr).GetString();
//   }
//
// expr->dump():
//  CXXStaticCastExpr 0x2b74e8e657b8 'class ResString' static_cast<class ResString> <ConstructorConversion>
//  `-CXXBindTemporaryExpr 0x2b74e8e65798 'class ResString' (CXXTemporary 0x2b74e8e65790)
//    `-CXXConstructExpr 0x2b74e8e65758 'class ResString' 'void (class ResString &&) noexcept(false)' elidable
//      `-MaterializeTemporaryExpr 0x2b74e8e65740 'class ResString' xvalue
//        `-CXXBindTemporaryExpr 0x2b74e8e65720 'class ResString' (CXXTemporary 0x2b74e8e65718)
//          `-ImplicitCastExpr 0x2b74e8e65700 'class ResString' <UserDefinedConversion>
//            `-CXXMemberCallExpr 0x2b74e8e656d8 'class ResString'
//              `-MemberExpr 0x2b74e8e656a0 '<bound member function type>' .operator ResString 0x2b74e8dc1f00
//                `-DeclRefExpr 0x2b74e8e65648 'struct ErrorResource_Impl' lvalue Var 0x2b74e8e653b0 'aEr' 'struct ErrorResource_Impl'
// expr->getSubExprAsWritten()->dump():
//  MaterializeTemporaryExpr 0x2b74e8e65740 'class ResString' xvalue
//  `-CXXBindTemporaryExpr 0x2b74e8e65720 'class ResString' (CXXTemporary 0x2b74e8e65718)
//    `-ImplicitCastExpr 0x2b74e8e65700 'class ResString' <UserDefinedConversion>
//      `-CXXMemberCallExpr 0x2b74e8e656d8 'class ResString'
//        `-MemberExpr 0x2b74e8e656a0 '<bound member function type>' .operator ResString 0x2b74e8dc1f00
//          `-DeclRefExpr 0x2b74e8e65648 'struct ErrorResource_Impl' lvalue Var 0x2b74e8e653b0 'aEr' 'struct ErrorResource_Impl'
//
// Copies code from Clang's lib/AST/Expr.cpp:
namespace detail {
  inline clang::Expr *skipImplicitTemporary(clang::Expr *expr) {
    // Skip through reference binding to temporary.
    if (clang::MaterializeTemporaryExpr *Materialize
                                  = clang::dyn_cast<clang::MaterializeTemporaryExpr>(expr))
      expr = Materialize->GetTemporaryExpr();

    // Skip any temporary bindings; they're implicit.
    if (clang::CXXBindTemporaryExpr *Binder = clang::dyn_cast<clang::CXXBindTemporaryExpr>(expr))
      expr = Binder->getSubExpr();

    return expr;
  }
}
inline clang::Expr *getSubExprAsWritten(clang::CastExpr *This) {
  clang::Expr *SubExpr = nullptr;
  clang::CastExpr *E = This;
  do {
    SubExpr = detail::skipImplicitTemporary(E->getSubExpr());

    // Conversions by constructor and conversion functions have a
    // subexpression describing the call; strip it off.
    if (E->getCastKind() == clang::CK_ConstructorConversion)
      SubExpr =
        detail::skipImplicitTemporary(clang::cast<clang::CXXConstructExpr>(SubExpr)->getArg(0));
    else if (E->getCastKind() == clang::CK_UserDefinedConversion) {
      assert((clang::isa<clang::CXXMemberCallExpr>(SubExpr) ||
              clang::isa<clang::BlockExpr>(SubExpr)) &&
             "Unexpected SubExpr for CK_UserDefinedConversion.");
      if (clang::isa<clang::CXXMemberCallExpr>(SubExpr))
        SubExpr = clang::cast<clang::CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
    }

    // If the subexpression we're left with is an implicit cast, look
    // through that, too.
  } while ((E = clang::dyn_cast<clang::ImplicitCastExpr>(SubExpr)));

  return SubExpr;
}
inline const clang::Expr *getSubExprAsWritten(const clang::CastExpr *This) {
  return getSubExprAsWritten(const_cast<clang::CastExpr *>(This));
}

}

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */