summaryrefslogtreecommitdiff
path: root/src/tools/cplusplus/Main.cpp
blob: a60d3c661e8c5135505ca33531effdc3c34485b2 (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

#include <QCoreApplication>
#include <QStringList>
#include <QTextDocument>
#include <QTextCursor>
#include <QTextBlock>
#include <QDir>
#include <QDebug>

#include <Control.h>
#include <Parser.h>
#include <AST.h>
#include <ASTVisitor.h>
#include <Symbols.h>
#include <CoreTypes.h>
#include <Literals.h>
#include <CppDocument.h>
#include <Overview.h>

#include <iostream>
#include <cstdlib>

using namespace CPlusPlus;

QTextCursor createCursor(TranslationUnit *unit, AST *ast, QTextDocument *document)
{
    unsigned startLine, startColumn, endLine, endColumn;
    unit->getTokenStartPosition(ast->firstToken(), &startLine, &startColumn);
    unit->getTokenEndPosition(ast->lastToken() - 1, &endLine, &endColumn);

    QTextCursor tc(document);
    tc.setPosition(document->findBlockByNumber(startLine - 1).position());
    tc.setPosition(document->findBlockByNumber(endLine - 1).position() + endColumn - 1,
                   QTextCursor::KeepAnchor);

    int charsToSkip = 0;
    forever {
        QChar ch = document->characterAt(tc.position() + charsToSkip);

        if (! ch.isSpace())
            break;

        ++charsToSkip;

        if (ch == QChar::ParagraphSeparator)
            break;
    }

    tc.setPosition(tc.position() + charsToSkip, QTextCursor::KeepAnchor);
    return tc;
}

class ASTNodes
{
public:
    ASTNodes(): base(0) {}

    ClassSpecifierAST *base; // points to "class AST"
    QList<ClassSpecifierAST *> deriveds; // n where n extends AST
    QList<QTextCursor> endOfPublicClassSpecifiers;
};

class FindASTNodes: protected ASTVisitor
{
public:
    FindASTNodes(Document::Ptr doc, QTextDocument *document)
        : ASTVisitor(doc->control()), document(document)
    {
    }

    ASTNodes operator()(AST *ast)
    {
        accept(ast);
        return _nodes;
    }

protected:
    virtual bool visit(ClassSpecifierAST *ast)
    {
        Class *klass = ast->symbol;
        Q_ASSERT(klass != 0);

        const QString className = oo(klass->name());

        if (className.endsWith("AST")) {
            if (className == QLatin1String("AST"))
                _nodes.base = ast;
            else {
                _nodes.deriveds.append(ast);

                AccessDeclarationAST *accessDeclaration = 0;
                for (DeclarationListAST *it = ast->member_specifiers; it; it = it->next) {
                    if (AccessDeclarationAST *decl = it->declaration->asAccessDeclaration()) {
                        if (tokenKind(decl->access_specifier_token) == T_PUBLIC)
                            accessDeclaration = decl;
                    }
                }

                if (! accessDeclaration)
                    qDebug() << "no access declaration for class:" << className;

                Q_ASSERT(accessDeclaration != 0);

                QTextCursor tc = createCursor(translationUnit(), accessDeclaration, document);
                tc.setPosition(tc.position());

                _nodes.endOfPublicClassSpecifiers.append(tc);
            }
        }

        return true;
    }

private:
    QTextDocument *document;
    ASTNodes _nodes;
    Overview oo;
};

class RemoveCastMethods: protected ASTVisitor
{
public:
    RemoveCastMethods(Document::Ptr doc, QTextDocument *document)
        : ASTVisitor(doc->control()), document(document) {}

    QList<QTextCursor> operator()(AST *ast)
    {
        _cursors.clear();
        accept(ast);
        return _cursors;
    }

protected:
    virtual bool visit(FunctionDefinitionAST *ast)
    {
        Function *fun = ast->symbol;
        const QString functionName = oo(fun->name());

        if (functionName.length() > 3 && functionName.startsWith(QLatin1String("as"))
            && functionName.at(2).isUpper()) {

            QTextCursor tc = createCursor(translationUnit(), ast, document);

            //qDebug() << qPrintable(tc.selectedText());
            _cursors.append(tc);
        }

        return true;
    }

private:
    QTextDocument *document;
    QList<QTextCursor> _cursors;
    Overview oo;
};

QStringList generateAST_H(const Snapshot &snapshot, const QDir &cplusplusDir)
{
    QStringList astDerivedClasses;

    QFileInfo fileAST_h(cplusplusDir, QLatin1String("AST.h"));
    Q_ASSERT(fileAST_h.exists());

    const QString fileName = fileAST_h.absoluteFilePath();

    QFile file(fileName);
    if (! file.open(QFile::ReadOnly))
        return astDerivedClasses;

    const QString source = QTextStream(&file).readAll();
    file.close();

    QTextDocument document;
    document.setPlainText(source);

    Document::Ptr doc = Document::create(fileName);
    const QByteArray preprocessedCode = snapshot.preprocessedCode(source, fileName);
    doc->setSource(preprocessedCode);
    doc->check();

    FindASTNodes process(doc, &document);
    ASTNodes astNodes = process(doc->translationUnit()->ast());

    RemoveCastMethods removeCastMethods(doc, &document);

    QList<QTextCursor> baseCastMethodCursors = removeCastMethods(astNodes.base);
    QMap<ClassSpecifierAST *, QList<QTextCursor> > cursors;
    QMap<ClassSpecifierAST *, QString> replacementCastMethods;

    Overview oo;

    QStringList castMethods;
    foreach (ClassSpecifierAST *classAST, astNodes.deriveds) {
        cursors[classAST] = removeCastMethods(classAST);
        const QString className = oo(classAST->symbol->name());
        const QString methodName = QLatin1String("as") + className.mid(0, className.length() - 3);
        replacementCastMethods[classAST] = QString("    virtual %1 *%2() { return this; }\n").arg(className, methodName);
        castMethods.append(QString("    virtual %1 *%2() { return 0; }\n").arg(className, methodName));

        astDerivedClasses.append(className);
    }

    if (! baseCastMethodCursors.isEmpty()) {
        castMethods.sort();
        for (int i = 0; i < baseCastMethodCursors.length(); ++i) {
            baseCastMethodCursors[i].removeSelectedText();
        }

        baseCastMethodCursors.first().insertText(castMethods.join(QLatin1String("")));
    }

    for (int classIndex = 0; classIndex < astNodes.deriveds.size(); ++classIndex) {
        ClassSpecifierAST *classAST = astNodes.deriveds.at(classIndex);

        // remove the cast methods.
        QList<QTextCursor> c = cursors.value(classAST);
        for (int i = 0; i < c.length(); ++i) {
            c[i].removeSelectedText();
        }

        astNodes.endOfPublicClassSpecifiers[classIndex].insertText(replacementCastMethods.value(classAST));
    }

    if (file.open(QFile::WriteOnly)) {
        QTextStream out(&file);
        out << document.toPlainText();
    }

    return astDerivedClasses;
}

class FindASTForwards: protected ASTVisitor
{
public:
    FindASTForwards(Document::Ptr doc, QTextDocument *document)
        : ASTVisitor(doc->control()), document(document)
    {}

    QList<QTextCursor> operator()(AST *ast)
    {
        accept(ast);
        return _cursors;
    }

protected:
    bool visit(SimpleDeclarationAST *ast)
    {
        if (ElaboratedTypeSpecifierAST *e = ast->decl_specifier_seq->asElaboratedTypeSpecifier()) {
            if (tokenKind(e->classkey_token) == T_CLASS && !ast->declarators) {
                QString className = oo(e->name->name);

                if (className.length() > 3 && className.endsWith(QLatin1String("AST"))) {
                    QTextCursor tc = createCursor(translationUnit(), ast, document);
                    _cursors.append(tc);
                }
            }
        }

        return true;
    }

private:
    QTextDocument *document;
    QList<QTextCursor> _cursors;
    Overview oo;
};

void generateASTFwd_h(const Snapshot &snapshot, const QDir &cplusplusDir, const QStringList &astDerivedClasses)
{
    QFileInfo fileASTFwd_h(cplusplusDir, QLatin1String("ASTfwd.h"));
    Q_ASSERT(fileASTFwd_h.exists());

    const QString fileName = fileASTFwd_h.absoluteFilePath();

    QFile file(fileName);
    if (! file.open(QFile::ReadOnly))
        return;

    const QString source = QTextStream(&file).readAll();
    file.close();

    QTextDocument document;
    document.setPlainText(source);

    Document::Ptr doc = Document::create(fileName);
    const QByteArray preprocessedCode = snapshot.preprocessedCode(source, fileName);
    doc->setSource(preprocessedCode);
    doc->check();

    FindASTForwards process(doc, &document);
    QList<QTextCursor> cursors = process(doc->translationUnit()->ast());

    for (int i = 0; i < cursors.length(); ++i)
        cursors[i].removeSelectedText();

    QString replacement;
    foreach (const QString &astDerivedClass, astDerivedClasses) {
        replacement += QString(QLatin1String("class %1;\n")).arg(astDerivedClass);
    }

    cursors.first().insertText(replacement);

    if (file.open(QFile::WriteOnly)) {
        QTextStream out(&file);
        out << document.toPlainText();
    }
}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QStringList files = app.arguments();
    files.removeFirst();

    if (files.isEmpty()) {
        std::cerr << "Usage: cplusplus [path to C++ front-end]" << std::endl;
        return EXIT_FAILURE;
    }

    QDir cplusplusDir(files.first());
    Snapshot snapshot;

    QStringList astDerivedClasses = generateAST_H(snapshot, cplusplusDir);
    astDerivedClasses.sort();
    generateASTFwd_h(snapshot, cplusplusDir, astDerivedClasses);
}