Parser.cpp 32.9 KB
Newer Older
Nikola Dinev's avatar
Nikola Dinev committed
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
#include "Module.h"
#include "Generator.hpp"

#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/CommandLine.h"

#include <memory>
#include <set>
#include <sstream>

using namespace clang;
using namespace clang::tooling;

// Apply a custom category to all command-line options so that they are the only ones displayed.
static llvm::cl::OptionCategory bindingsOptions("Bindings generation options");
static llvm::cl::opt<std::string> hintsPath("hints", llvm::cl::cat(bindingsOptions),
                                            llvm::cl::desc("Path to hints file"));
static llvm::cl::opt<std::string>
    outputDir("o", llvm::cl::cat(bindingsOptions),
              llvm::cl::desc("Output directory, defaults to the current working directory."));
static llvm::cl::opt<std::string> moduleName(
    "name", llvm::cl::cat(bindingsOptions),
    llvm::cl::desc("Name of the module. This option or the pyname option must be specified."));
static llvm::cl::opt<std::string> pythonModuleName(
    "pyname", llvm::cl::cat(bindingsOptions),
    llvm::cl::desc("Name that should be given assigned to the generated python module. \"py\" "
                   "will be prepended to the value of the name option if not specified"));
34
35
36
37
38
static llvm::cl::opt<bool> noModule(
    "no-module", llvm::cl::cat(bindingsOptions),
    llvm::cl::desc("When specified the code for module generation will be omited, instead only the "
                   "binding definitions will be created. The definitions can later be added to an "
                   "arbitrary module by calling add_definitions_<pyname>(module)."));
Nikola Dinev's avatar
Nikola Dinev committed
39
40
41
42
43
44
45
46

static llvm::cl::extrahelp commonHelp(CommonOptionsParser::HelpMessage);

static elsa::Module m;

class ParserBase
{
public:
47
    static std::string lexicallyNormalPath(std::string path)
Nikola Dinev's avatar
Nikola Dinev committed
48
49
    {

50
        std::filesystem::path p(path);
Nikola Dinev's avatar
Nikola Dinev committed
51

52
53
54
55
56
57
        // normalize path so that it does not contain parent directory references (..)
#if INCLUDE_STD_FILESYSTEM_EXPERIMENTAL
        return ParserBase::lexicallyNormalPathFallback(p.generic_string());
#else
        return p.lexically_normal().generic_string();
#endif
Nikola Dinev's avatar
Nikola Dinev committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
    }

protected:
    ParserBase(ASTContext* context) : context{context}, printingPolicy{context->getLangOpts()}
    {
        printingPolicy.PrintCanonicalTypes = 1;
    }

    std::string getNamespaceStrippedName(const TagDecl* declaration)
    {
        std::string namespaceStrippedName = declaration->getNameAsString();

        auto parent = declaration->getParent();
        while (parent->isRecord()) {
            auto rec = dyn_cast<CXXRecordDecl>(parent);
            namespaceStrippedName = getNamespaceStrippedName(rec) + "::" + namespaceStrippedName;
            parent = parent->getParent();
        }

        if (auto ctsd = dyn_cast<ClassTemplateSpecializationDecl>(declaration)) {
            namespaceStrippedName += "<";
            for (std::size_t i = 0; i < ctsd->getTemplateArgs().size(); i++) {

                const auto& tmpArg = ctsd->getTemplateArgs()[i];
82
                llvm::SmallString<1024> nameSmallStr(namespaceStrippedName);
Nikola Dinev's avatar
Nikola Dinev committed
83
84
                switch (tmpArg.getKind()) {
                    case TemplateArgument::ArgKind::Integral:
85
86
                        tmpArg.getAsIntegral().toString(nameSmallStr);
                        namespaceStrippedName = nameSmallStr.c_str();
Nikola Dinev's avatar
Nikola Dinev committed
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
                        break;

                    case TemplateArgument::ArgKind::Type:
                        if (tmpArg.getAsType()->getAsCXXRecordDecl() != nullptr) {
                            namespaceStrippedName +=
                                getNamespaceStrippedName(tmpArg.getAsType()->getAsCXXRecordDecl());
                        } else {
                            namespaceStrippedName += tmpArg.getAsType().getAsString();
                        }
                        break;

                    default:
                        // TODO: add error message if another argkind is encountered
                        break;
                }

                if (i < ctsd->getTemplateArgs().size() - 1)
                    namespaceStrippedName += ", ";
            }
            namespaceStrippedName += ">";
        }

        return namespaceStrippedName;
    }

    std::string fullyQualifiedId(const QualType& qualType)
    {
        auto id = qualType.getAsString(printingPolicy);

        // remove spaces before references
        for (auto pos = id.find(" &"); pos != std::string::npos; pos = id.find(" &")) {
            id.erase(pos, 1);
        }

        // remove spaces before template closing brackets
        for (auto pos = id.find(" >"); pos != std::string::npos; pos = id.find(" >")) {
            id.erase(pos, 1);
        }

        return id;
    }

    std::string getHeaderLocation(CXXRecordDecl* declaration)
    {
        std::string location;
        auto ctsd = dyn_cast<ClassTemplateSpecializationDecl>(declaration);
        if (ctsd
            && (ctsd->getSpecializationKind() == TSK_ExplicitInstantiationDeclaration
                || ctsd->getSpecializationKind() == TSK_ExplicitInstantiationDefinition
                || ctsd->getSpecializationKind() == TSK_ImplicitInstantiation)) {
            // if this is a a template instantiation, include the ClassTemplateDecl instead
            ClassTemplateDecl* ctd = *ctsd->getInstantiatedFrom().getAddrOfPtr1();
            location = ctd->getBeginLoc().printToString(context->getSourceManager());
        } else {
            location = declaration->getBeginLoc().printToString(context->getSourceManager());
        }

144
        return lexicallyNormalPath(getAbsolutePath(location.substr(0, location.find(":"))));
Nikola Dinev's avatar
Nikola Dinev committed
145
146
147
148
149
150
151
152
153
154
155
156
157
    }

    std::string getRefQualifierString(RefQualifierKind refQual)
    {
        switch (refQual) {
            case RQ_None:
                return elsa::Module::Function::RQ_NONE;
            case RQ_LValue:
                return elsa::Module::Function::RQ_LVAL;
            case RQ_RValue:
                return elsa::Module::Function::RQ_RVAL;
            default:
                assert(false && ("ref-qualifier kind not supported"));
158
                return elsa::Module::Function::RQ_NONE;
Nikola Dinev's avatar
Nikola Dinev committed
159
160
161
        }
    }

162
163
164
165
    // encountered tags' typenames are added to the map as soon as encountered, but the pointer to
    // the object remains a nullptr until the record is fully processed
    static std::map<std::string, elsa::Module::Record*> encounteredRecords;
    static std::map<std::string, elsa::Module::Enum*> encounteredEnums;
Nikola Dinev's avatar
Nikola Dinev committed
166
167
    ASTContext* context;
    PrintingPolicy printingPolicy;
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191

private:
    // returns the lexically normal path similarly to std::filesystem::path::lexically_normal
    static std::string lexicallyNormalPathFallback(std::string path)
    {
        while (path.find("..") != std::string::npos) {
            auto posDots = path.find("..");

            std::size_t eraseEnd = posDots + 2;
            std::size_t numDots = 1;
            while (path.rfind("..", posDots) == posDots - 3) {
                posDots = path.rfind("..", posDots);
                numDots++;
            }

            std::size_t eraseStart = posDots - 1;
            for (int i = 0; i < numDots; i++)
                eraseStart = path.rfind("/", eraseStart - 1);

            path.erase(eraseStart, eraseEnd - eraseStart);
        }

        return path;
    }
Nikola Dinev's avatar
Nikola Dinev committed
192
193
};

194
195
196
std::map<std::string, elsa::Module::Record*> ParserBase::encounteredRecords = {};
std::map<std::string, elsa::Module::Enum*> ParserBase::encounteredEnums = {};

Nikola Dinev's avatar
Nikola Dinev committed
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
class ModuleParser : public RecursiveASTVisitor<ModuleParser>, public ParserBase
{
public:
    explicit ModuleParser(ASTContext* context) : ParserBase{context} {}

    bool shouldVisitTemplateInstantiations() { return true; };

    bool shouldVisitImplicitCode() { return true; }

    bool VisitCXXRecordDecl(CXXRecordDecl* declaration)
    {
        // ignore record declarations from includes
        if (!context->getSourceManager().isInMainFile(declaration->getLocation()))
            return true;

        // ignore lambdas (implicitly generated lambda classes may be visited if the
        // visitImplicitCode option is set)
        if (declaration->isLambda())
            return true;

        // ignore template declarations, only template instantiations carry the necessary
        // information for bindings generation
        if (declaration->isTemplated())
            return true;

        FullSourceLoc fullLocation = context->getFullLoc(declaration->getBeginLoc());
        if (!fullLocation.isValid())
            return true;

226
        if (declaration->isClass() || declaration->isStruct() || declaration->isEnum()) {
Nikola Dinev's avatar
Nikola Dinev committed
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
            parseRecord(declaration);
        }
        return true;
    }

    bool VisitCXXMethodDecl(CXXMethodDecl* method)
    {
        // ignore method declarations from includes
        if (!context->getSourceManager().isInMainFile(method->getLocation()))
            return true;

        if (method->isTemplateInstantiation())
            appendMethodTemplateInstantiation(method);

        return true;
    }

    void parseDeclForQualType(QualType type)
    {
        type = type.getNonReferenceType();
        if (type->isRecordType()) {
            parseRecord(type->getAsCXXRecordDecl());
        } else if (type->isEnumeralType() || type->isScopedEnumeralType()) {
            parseEnum(dyn_cast<EnumDecl>(type->getAsTagDecl()));
        } else {
            return;
        }
    }

    void parseEnum(EnumDecl* declaration)
    {

        auto id = fullyQualifiedId(context->getEnumType(declaration));
260
        if (encounteredEnums.find(id) != encounteredEnums.end())
Nikola Dinev's avatar
Nikola Dinev committed
261
262
            return;

263
264
265
266
267
268
269
        // only record an enum when its in the current module,
        // otherwise we get double-definitions when they are included
        // between modules
        if (fileLocation(declaration).find(m.path) != 0) {
            return;
        }

Nikola Dinev's avatar
Nikola Dinev committed
270
271
272
273
274
275
        auto e = std::make_unique<elsa::Module::Enum>();

        e->name = id;
        e->namespaceStrippedName = getNamespaceStrippedName(declaration);
        e->isScoped = declaration->isScoped();
        for (auto enumerator : declaration->enumerators()) {
276
277
278
            llvm::SmallString<32> valueAsStr;
            enumerator->getInitVal().toString(valueAsStr);
            e->values.emplace(enumerator->getNameAsString(), valueAsStr.c_str());
Nikola Dinev's avatar
Nikola Dinev committed
279
280
        }

281
282
        m.enums.push_back(std::move(e));
        encounteredEnums.emplace(m.enums.back()->name, m.enums.back().get());
Nikola Dinev's avatar
Nikola Dinev committed
283
284
285
286
287
288
289
290
    }

    void parseRecord(CXXRecordDecl* declaration)
    {
        if (!shouldBeRegisteredInCurrentModule(declaration)) {
            return;
        }

291
292
293
294
295
        auto includeFile = getHeaderLocation(declaration);
        if (includeFile.find(m.path) == 0) {
            m.includes.insert(includeFile);
        }

Nikola Dinev's avatar
Nikola Dinev committed
296
297
298
299
300
        auto r = std::make_unique<elsa::Module::Record>();
        auto id = fullyQualifiedId(context->getRecordType(declaration));

        // register tag as encountered, nullptr as second argument means it is still not fully
        // processed
301
        encounteredRecords.emplace(id, nullptr);
Nikola Dinev's avatar
Nikola Dinev committed
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
        r->name = id;
        r->namespaceStrippedName = getNamespaceStrippedName(declaration);

        if (declaration->hasDefinition()) {
            for (auto& base : declaration->bases()) {
                if (base.getAccessSpecifier() == AS_public) {
                    r->bases.push_back(fullyQualifiedId(base.getType()));
                    parseRecord(base.getType().getCanonicalType()->getAsCXXRecordDecl());
                }
            }
        }

        bool isAbstract = false;

        for (auto decl : declaration->decls()) {
317
318
319
320
321
322
323
324
325
            if (dyn_cast<UsingDecl>(decl)) {
                for (auto shadow : dyn_cast<UsingDecl>(decl)->shadows()) {
                    auto target = shadow->getTargetDecl();
                    // ignore non-public shadows as well as copy constructors
                    if (decl->getAccess() == AS_public
                        && (dyn_cast<CXXConstructorDecl>(target) == nullptr
                            || !dyn_cast<CXXConstructorDecl>(target)->isCopyConstructor())) {
                        handleMemberDeclaration(target, *r);
                    }
Nikola Dinev's avatar
Nikola Dinev committed
326
                }
327
328
            } else {
                handleMemberDeclaration(decl, *r);
Nikola Dinev's avatar
Nikola Dinev committed
329
330
331
            }
        }

332
        m.records.push_back(std::move(r));
Nikola Dinev's avatar
Nikola Dinev committed
333
334

        // update encountered tags pointer
335
        encounteredRecords[id] = m.records.back().get();
Nikola Dinev's avatar
Nikola Dinev committed
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360

        // register unencountered template type parameters
        if (auto ctsd = dyn_cast<ClassTemplateSpecializationDecl>(declaration)) {

            // get associated class template declaration tparam list
            auto tparamList = ctsd->getSpecializedTemplate()->getTemplateParameters();

            // check if template args match default args
            bool tparamsMatchDefaults = true;
            for (unsigned int i = 0; i < tparamList->size(); i++) {
                if (auto ttpd = dyn_cast<TemplateTypeParmDecl>(tparamList->getParam(i))) {
                    // TODO: look for a better way to compare types
                    if (!ttpd->hasDefaultArgument()
                        || fullyQualifiedId(ttpd->getDefaultArgument())
                               != fullyQualifiedId(ctsd->getTemplateArgs()[i].getAsType())) {
                        tparamsMatchDefaults = false;
                        break;
                    }
                } else {
                    tparamsMatchDefaults = false;
                    break;
                }
            }

            if (tparamsMatchDefaults)
361
                m.records.back()->alias = ctsd->getSpecializedTemplate()->getNameAsString();
Nikola Dinev's avatar
Nikola Dinev committed
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409

            for (int i = 0; i < ctsd->getTemplateArgs().size(); i++) {
                if (ctsd->getTemplateArgs()[i].getKind() != TemplateArgument::ArgKind::Type)
                    continue;

                const auto type = ctsd->getTemplateArgs()[i].getAsType();
                parseDeclForQualType(type);
            }
        }
    }

    void parseMethod(const CXXMethodDecl* method, elsa::Module::Record& r)
    {
        if (method->isPure())
            r.isAbstract = true;

        // ignore non-public methods, destructors, and conversion functions
        if (method->getAccess() == AS_public && !method->isDeleted()
            && !method->isDeletedAsWritten() && dyn_cast<CXXDestructorDecl>(method) == nullptr
            && dyn_cast<CXXConversionDecl>(method) == nullptr) {

            // skip methods that are ignored in class hints
            if (m.classHints.find(r.name) != m.classHints.end()) {
                const auto& hints = m.classHints[r.name];
                if (hints.ignoredMethods.find(method->getNameAsString())
                    != hints.ignoredMethods.end())
                    return;
            }

            elsa::Module::Function f;
            f.name = method->getNameAsString();
            f.isStatic = method->isStatic();
            f.returnType = fullyQualifiedId(method->getReturnType());
            f.isConst = method->isConst();
            f.refQualifier = getRefQualifierString(method->getRefQualifier());
            f.isConstructor = (dyn_cast<CXXConstructorDecl>(method) != nullptr);
            f.isTemplate = method->isTemplated();
            f.posFirstNonBindableDefaultArg = method->getNumParams();
            parseDeclForQualType(method->getReturnType());

            for (auto param : method->parameters()) {
                f.params.emplace_back(param->getQualifiedNameAsString(),
                                      fullyQualifiedId(param->getType()));

                if (param->hasDefaultArg()) {
                    f.numDefaultArgs++;

                    if (f.posFirstNonBindableDefaultArg == method->getNumParams()) {
410
411
412
                        auto defaultArg = param->hasUninstantiatedDefaultArg()
                                              ? param->getUninstantiatedDefaultArg()
                                              : param->getDefaultArg();
Nikola Dinev's avatar
Nikola Dinev committed
413
414
415
416
417

                        Expr::EvalResult result;
                        if (defaultArg && !defaultArg->isInstantiationDependent()
                            && !defaultArg->isValueDependent() && !defaultArg->isTypeDependent()
                            && defaultArg->EvaluateAsRValue(result, *context)
418
419
420
                            && !result.hasSideEffects()
                            && (result.Val.isInt() || result.Val.isFloat()
                                || result.Val.isComplexInt() || result.Val.isComplexFloat())) {
Nikola Dinev's avatar
Nikola Dinev committed
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443

                            f.params.back().defaultValue =
                                result.Val.getAsString(*context, param->getType());
                        } else {
                            f.posFirstNonBindableDefaultArg = f.params.size() - 1;
                        }
                    }
                }

                parseDeclForQualType(param->getType());
            }

            auto fType = method->getType()->getCanonicalTypeInternal().getAsString();
            r.methods.emplace(fType + " " + f.name, f);
        }
    }

protected:
    void appendMethodTemplateInstantiation(CXXMethodDecl* method)
    {
        auto parent = method->getParent();
        auto id = fullyQualifiedId(context->getRecordType(parent));

444
445
        auto it = encounteredRecords.find(id);
        if (it != encounteredRecords.end()) {
Nikola Dinev's avatar
Nikola Dinev committed
446
            // we know this is a Record
447
            auto r = it->second;
Nikola Dinev's avatar
Nikola Dinev committed
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
            if (r == nullptr)
                return;

            auto fType = method->getType()->getCanonicalTypeInternal().getAsString();
            if (r->methods.find(fType + " " + method->getNameAsString()) == r->methods.end())
                parseMethod(method, *r);
        } else {
            // we might encounter implicitly templated lambdas here
            if (!parent->isLambda()) {
                m.includes.insert(getHeaderLocation(parent));
                parseRecord(parent);
            }
        }
    };

    bool shouldBeRegisteredInCurrentModule(const CXXRecordDecl* declaration,
                                           bool considerEncountered = false)
    {
        auto id = fullyQualifiedId(context->getRecordType(declaration));

        auto type = context->getRecordType(declaration);
        type.removeLocalConst();
        type.removeLocalRestrict();
        type.removeLocalVolatile();
        auto noFastQualId = fullyQualifiedId(type);

        // include header for Eigen if necessary
        if (noFastQualId.find("Eigen::") == 0)
            m.pybindIncludes.insert("pybind11/eigen.h");

        // do not register STL types but add necessary pybind includes
        if (context->getFullLoc(declaration->getBeginLoc()).isInSystemHeader()) {

481
482
483
484
            auto inPybindSTL = {"std::vector<", "std::deque<",         "std::list<",
                                "std::array<",  "std::set<",           "std::unordered_set<",
                                "std::map<",    "std::unordered_map<", "std::optional<",
                                "std::variant<"};
Nikola Dinev's avatar
Nikola Dinev committed
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514

            if (noFastQualId.find("std::complex<") == 0) {
                m.pybindIncludes.insert("pybind11/complex.h");
            } else if (noFastQualId.find("std::function<") == 0) {
                m.pybindIncludes.insert("pybind11/functional.h");
            } else if (noFastQualId.find("std::chrono::duration<") == 0
                       || noFastQualId.find("std::chrono::time_point<") == 0) {
                m.pybindIncludes.insert("pybind11/chrono.h");
            } else if (m.pybindIncludes.find("pybind11/stl.h") == m.pybindIncludes.end()
                       && std::any_of(inPybindSTL.begin(), inPybindSTL.end(),
                                      [&noFastQualId](const std::string& comp) {
                                          return noFastQualId.find(comp) == 0;
                                      })) {
                m.pybindIncludes.insert("pybind11/stl.h");
            }

            // parse template arguments of STL types
            if (auto ctsd = dyn_cast<ClassTemplateSpecializationDecl>(declaration)) {
                for (int i = 0; i < ctsd->getTemplateArgs().size(); i++) {
                    if (ctsd->getTemplateArgs()[i].getKind() != TemplateArgument::ArgKind::Type)
                        continue;

                    const auto type = ctsd->getTemplateArgs()[i].getAsType();
                    parseDeclForQualType(type);
                }
            }

            return false;
        }

515
        if (encounteredRecords.find(id) != encounteredRecords.end())
Nikola Dinev's avatar
Nikola Dinev committed
516
517
            return considerEncountered ? true : false;

518
519
        // otherwise, register in this module if declaration is contained in the module path or
        // a template argument should be registered in this module
Nikola Dinev's avatar
Nikola Dinev committed
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
        if (fileLocation(declaration).find(m.path) != 0) {
            if (auto ctsd = dyn_cast<ClassTemplateSpecializationDecl>(declaration)) {
                for (int i = 0; i < ctsd->getTemplateArgs().size(); i++) {
                    if (ctsd->getTemplateArgs()[i].getKind() != TemplateArgument::ArgKind::Type)
                        continue;

                    const auto decl = ctsd->getTemplateArgs()[i].getAsType()->getAsCXXRecordDecl();

                    // builtin types (e.g. float) do not have an associated declaration
                    if (decl != nullptr && shouldBeRegisteredInCurrentModule(decl, true))
                        return true;
                }
            }
            return false;
        }

        // printStuff(declaration);
        return true;
    }

540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
    void handleMemberDeclaration(Decl* decl, elsa::Module::Record& r)
    {
        if (dyn_cast<CXXMethodDecl>(decl)) {
            auto method = dyn_cast<CXXMethodDecl>(decl);
            parseMethod(method, r);
        } else if (dyn_cast<FunctionTemplateDecl>(decl)) {
            const auto ftd = dyn_cast<FunctionTemplateDecl>(decl);
            const auto method = dyn_cast<CXXMethodDecl>(ftd->getTemplatedDecl());
            parseMethod(method, r);
            for (const auto spec : ftd->specializations()) {
                const auto method = dyn_cast<CXXMethodDecl>(spec);
                parseMethod(method, r);
            }
        }
    }

Nikola Dinev's avatar
Nikola Dinev committed
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
    std::string fileLocation(const TagDecl* declaration)
    {
        const auto location = declaration->getBeginLoc().printToString(context->getSourceManager());

        // format of location is path:line:column
        auto path = tooling::getAbsolutePath(location.substr(0, location.find(":")));

        // normalize path so that it does not contain parent directory references (..)
        while (path.find("..") != std::string::npos) {
            auto posDots = path.find("..");

            std::size_t eraseEnd = posDots + 2;
            std::size_t numDots = 1;
            while (path.rfind("..", posDots) == posDots - 3) {
                posDots = path.rfind("..", posDots);
                numDots++;
            }

            std::size_t eraseStart = posDots - 1;
            for (int i = 0; i < numDots; i++)
                eraseStart = path.rfind("/", eraseStart - 1);

            path.erase(eraseStart, eraseEnd - eraseStart);
        }

        return path;
    }
};

class HintsParser : public clang::RecursiveASTVisitor<HintsParser>, public ParserBase
{
public:
    explicit HintsParser(ASTContext* context) : ParserBase{context} {}

    bool shouldVisitTemplateInstantiations() { return true; }

    bool shouldVisitImplicitCode() { return true; }

    bool VisitCXXRecordDecl(CXXRecordDecl* declaration)
    {
        // skip records from includes
        if (!context->getSourceManager().isInMainFile(declaration->getLocation()))
            return true;

        // ignore lambdas (implicitly generated lambda classes may be visited if the
        // visitImplicitCode option is set)
        if (declaration->isLambda())
            return true;

        // ignore template declarations, only template instantiations carry the necessary
        // information for bindings generation
        if (declaration->isTemplated())
            return true;

        // we only care about ClassHints and ModuleHints
611
        bool isModuleHintsDescendant = false;
Nikola Dinev's avatar
Nikola Dinev committed
612
613
614
615
616
617
618
619
620
621
622
        bool isClassHintsDescendant = false;
        CXXRecordDecl* hintsFor;
        if (declaration->hasDefinition()) {
            for (const auto& base : declaration->bases()) {
                if (base.getType()->getAsCXXRecordDecl() != nullptr) {
                    const auto baseDecl = base.getType()->getAsCXXRecordDecl();
                    if (baseDecl->getNameAsString() == "ClassHints") {
                        isClassHintsDescendant = true;
                        const auto ctsd = dyn_cast<ClassTemplateSpecializationDecl>(baseDecl);
                        hintsFor = ctsd->getTemplateArgs()[0].getAsType()->getAsCXXRecordDecl();
                        break;
623
624
625
                    } else if (baseDecl->getNameAsString() == "ModuleHints") {
                        isModuleHintsDescendant = true;
                        break;
Nikola Dinev's avatar
Nikola Dinev committed
626
627
628
629
630
                    }
                }
            }
        }

631
        if (isModuleHintsDescendant || isClassHintsDescendant) {
Nikola Dinev's avatar
Nikola Dinev committed
632
633
634
            auto location = declaration->getBeginLoc().printToString(context->getSourceManager());
            m.moduleHints.includePath = location.substr(0, location.find(":"));

635
            if (isModuleHintsDescendant) {
Nikola Dinev's avatar
Nikola Dinev committed
636
637
                for (auto method : declaration->methods()) {
                    if (method->getNameAsString() == "addCustomFunctions") {
638
639
                        m.moduleHints.moduleHintsName =
                            fullyQualifiedId(context->getRecordType(declaration));
Nikola Dinev's avatar
Nikola Dinev committed
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
                        m.moduleHints.definesGlobalCustomFunctions = true;
                    }
                }
                return true;
            }
        } else {
            return true;
        }

        elsa::Module::ClassHints classHints;
        classHints.recordName = fullyQualifiedId(context->getRecordType(hintsFor));
        classHints.classHintsName = fullyQualifiedId(context->getRecordType(declaration));

        for (const auto decl : declaration->decls()) {
            if (dyn_cast<VarDecl>(decl)) {
                auto varDecl = dyn_cast<VarDecl>(decl);

                if (varDecl->getNameAsString() == "ignoreMethods") {

659
660
661
662
663
664
665
                    auto initListExpr = dyn_cast<InitListExpr>(
                        dyn_cast<InitListExpr>(varDecl->getInit())->getInit(0)->IgnoreImplicit());

                    if (initListExpr) {
                        for (auto arg : initListExpr->inits()) {

                            arg = arg->IgnoreImplicit();
Nikola Dinev's avatar
Nikola Dinev committed
666
667
668
669
670
671
672
673
674
675
676

                            if (!dyn_cast<StringLiteral>(arg))
                                assert(false
                                       && "ignoreMethods initializer contains non-string literals");

                            auto methodName = dyn_cast<StringLiteral>(arg)->getString().str();
                            classHints.ignoredMethods.insert(methodName);
                        }
                    }
                    // this may be just a single StringLiteral (and not packed in a
                    // CXXConstructExpr) when we are ignoring only a single method
677
678
679
680
681
                    else if (dyn_cast<StringLiteral>(varDecl->getInit()->IgnoreImplicit())) {
                        auto methodName =
                            dyn_cast<StringLiteral>(varDecl->getInit()->IgnoreImplicit())
                                ->getString()
                                .str();
Nikola Dinev's avatar
Nikola Dinev committed
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
                        classHints.ignoredMethods.insert(methodName);
                    } else {
                        assert(false && "ignoreMethods not inline initialized");
                    }
                }
            }

            else if (dyn_cast<FunctionTemplateDecl>(decl)) {
                auto ftd = dyn_cast<FunctionTemplateDecl>(decl);
                if (ftd->getNameAsString() == "addCustomMethods"
                    || ftd->getNameAsString() == "exposeBufferInfo") {
                    auto addCustomMethods = dyn_cast<CXXMethodDecl>(ftd->getTemplatedDecl());

                    assert(addCustomMethods->isStatic());

                    assert(addCustomMethods->getNumParams() == 1);

                    auto pyClass = *addCustomMethods->param_begin();

                    assert(pyClass->getType().getAsString().substr(0, 11) == "py::class_<");

                    if (ftd->getNameAsString() == "addCustomMethods") {
                        classHints.definesCustomMethods = true;
                    } else {
                        classHints.exposesBufferInfo = true;
                    }
                }
            }
        }

        m.classHints.emplace(classHints.recordName, classHints);

        return true;
    }
};

class ModuleParserConsumer : public clang::ASTConsumer
{
public:
    explicit ModuleParserConsumer(ASTContext* context) : visitor(context) {}

    void HandleTranslationUnit(clang::ASTContext& context) override
    {
        visitor.TraverseDecl(context.getTranslationUnitDecl());
    }

private:
    ModuleParser visitor;
};

class HintsParserConsumer : public clang::ASTConsumer
{
public:
    explicit HintsParserConsumer(ASTContext* context) : visitor(context) {}

    void HandleTranslationUnit(clang::ASTContext& context) override
    {
        visitor.TraverseDecl(context.getTranslationUnitDecl());
    }

private:
    HintsParser visitor;
};

class ModuleParserAction : public clang::ASTFrontendAction
{
public:
    std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(clang::CompilerInstance& Compiler,
                                                          llvm::StringRef InFile) override
    {
752
753
754
755
756
757
758
        // speed up parsing by skipping over function bodies
        Compiler.getFrontendOpts().SkipFunctionBodies = true;

        // workaround for omp bug in older clang versions(<10?). see
        // https://github.com/clangd/clangd/issues/173

        Compiler.getLangOpts().OpenMP = false;
Nikola Dinev's avatar
Nikola Dinev committed
759
760
761
762
763
764
765
766
767
768
769
        return std::unique_ptr<clang::ASTConsumer>(
            new ModuleParserConsumer(&Compiler.getASTContext()));
    }
};

class HintsParserAction : public clang::ASTFrontendAction
{
public:
    std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(clang::CompilerInstance& Compiler,
                                                          llvm::StringRef InFile) override
    {
770
771
772
773
774
775
776
        // speed up parsing by skipping over function bodies
        Compiler.getFrontendOpts().SkipFunctionBodies = true;

        // workaround for omp bug in older clang versions(<10?). see
        // https://github.com/clangd/clangd/issues/173
        Compiler.getLangOpts().OpenMP = false;

Nikola Dinev's avatar
Nikola Dinev committed
777
778
779
780
781
782
783
        return std::unique_ptr<clang::ASTConsumer>(
            new HintsParserConsumer(&Compiler.getASTContext()));
    }
};

int main(int argc, const char** argv)
{
784
785
    noModule.setInitialValue(false);

786
#if LLVM_VERSION_MAJOR < 13
Nikola Dinev's avatar
Nikola Dinev committed
787
    CommonOptionsParser optionsParser(argc, argv, bindingsOptions);
788
789
790
791
792
793
#else
    auto optionsParserExp = CommonOptionsParser::create(argc, argv, bindingsOptions);
    assert((optionsParserExp) && "Failed to parse command line arguments");

    auto& optionsParser = optionsParserExp.get();
#endif
Nikola Dinev's avatar
Nikola Dinev committed
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809

    assert((!moduleName.empty() || !pythonModuleName.empty())
           && "-name or -pyname should be specified");

    if (!moduleName.empty()) {
        m.name = moduleName;
        if (pythonModuleName.empty())
            m.pythonName = "py" + m.name;
    }

    if (!pythonModuleName.empty()) {
        m.pythonName = pythonModuleName;
        if (m.name.empty())
            m.name = m.pythonName;
    }

810
811
    m.noPythonModule = noModule.getValue();

Nikola Dinev's avatar
Nikola Dinev committed
812
    if (!hintsPath.empty()) {
Nikola Dinev's avatar
Nikola Dinev committed
813
814
        ClangTool hintsParser(optionsParser.getCompilations(), std::vector{hintsPath.getValue()});
        // hintsParser.appendArgumentsAdjuster(optionsParser.getArgumentsAdjuster());
Nikola Dinev's avatar
Nikola Dinev committed
815

816
        auto factory = newFrontendActionFactory<HintsParserAction>();
817
818
819
820
821
        int retCode = hintsParser.run(factory.get());

        // fail with the corresponding error code when the hints file can't be parsed
        if (retCode)
            return retCode;
Nikola Dinev's avatar
Nikola Dinev committed
822
823
824
825
826
    }

    ClangTool tool(optionsParser.getCompilations(), optionsParser.getSourcePathList());
    tool.appendArgumentsAdjuster(optionsParser.getArgumentsAdjuster());

827
828
829
830
    std::filesystem::path p(ParserBase::lexicallyNormalPath(
        tooling::getAbsolutePath(optionsParser.getSourcePathList().front())));

    m.path = p.parent_path().generic_string();
Nikola Dinev's avatar
Nikola Dinev committed
831
832
833

    // find the longest lexically normal common parent path for all specified source files
    for (std::size_t i = 1; i < optionsParser.getSourcePathList().size(); i++) {
834
835
836
837
838
839
840

        std::filesystem::path p(ParserBase::lexicallyNormalPath(
            tooling::getAbsolutePath(optionsParser.getSourcePathList()[i])));

        std::string path = p.parent_path().generic_string();

        while (m.path.size() > path.size() && m.path.find(path) == 0)
Nikola Dinev's avatar
Nikola Dinev committed
841
842
843
            m.path = m.path.substr(0, m.path.rfind("/"));
    }

844
    auto factory = newFrontendActionFactory<ModuleParserAction>();
845
846
847
848
849
    int retCode = tool.run(factory.get());

    // fail with the corresponding error code when a file can't be parsed
    if (retCode)
        return retCode;
Nikola Dinev's avatar
Nikola Dinev committed
850
851

    Generator::generateBindingsForModule(m, outputDir);
852
853

    return 0;
854
}