File: correctionfilegenerator.cpp

package info (click to toggle)
kdevelop-python 24.12.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 12,640 kB
  • sloc: python: 183,048; cpp: 18,798; xml: 140; sh: 14; makefile: 9
file content (496 lines) | stat: -rw-r--r-- 17,029 bytes parent folder | download
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
359
360
361
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
/*
    SPDX-FileCopyrightText: 2013 Sven Brauch <svenbrauch@googlemail.com>

    SPDX-License-Identifier: LGPL-2.0-or-later
*/

#include "correctionfilegenerator.h"

#include <QAction>
#include <QTemporaryFile>

#include <language/backgroundparser/backgroundparser.h>
#include <language/duchain/duchainlock.h>
#include <language/duchain/duchainutils.h>
#include <language/interfaces/codecontext.h>
#include <interfaces/icore.h>
#include <interfaces/idocumentcontroller.h>
#include <interfaces/ilanguagecontroller.h>
#include <interfaces/iprojectcontroller.h>
#include <parser/parsesession.h>

#include <KTextEditor/Document>

#include "duchain/helpers.h"
#include "parser/codehelpers.h"

#include <QDebug>
#include <QStack>
#include "codegendebug.h"

using namespace KDevelop;

namespace Python {

TypeCorrection::TypeCorrection()
    : m_ui(new Ui::CorrectionWidget)
{
}

TypeCorrection &TypeCorrection::self()
{
    static TypeCorrection instance;
    return instance;
}

void TypeCorrection::doContextMenu(ContextMenuExtension &extension, Context *context)
{
    if ( DeclarationContext* declContext = dynamic_cast<DeclarationContext*>(context) ) {
        qRegisterMetaType<KDevelop::IndexedDeclaration>("KDevelop::IndexedDeclaration");

        DUChainReadLocker lock;

        KDevelop::Declaration* declaration = declContext->declaration().data();

        if ( declaration && (declaration->kind() == Declaration::Instance
                             || (declaration->kind() == Declaration::Type
                                 && declaration->abstractType()->whichType() == AbstractType::TypeFunction)) ) {
            QAction* action = new QAction(i18n("Specify type for \"%1\"...", declaration->qualifiedIdentifier().toString()), nullptr);
            action->setData(QVariant::fromValue(IndexedDeclaration(declaration)));
            action->setIcon(QIcon::fromTheme(QStringLiteral("code-class")));
            connect(action, &QAction::triggered, this, &TypeCorrection::executeSpecifyTypeAction);

            extension.addAction(ContextMenuExtension::ExtensionGroup, action);
        }
    }
}

void TypeCorrection::executeSpecifyTypeAction()
{
    QAction* action = qobject_cast<QAction*>(sender());
    if ( ! action ) {
        qCWarning(KDEV_PYTHON_CODEGEN) << "slot not invoked by triggering a QAction, should not happen"; // :)
        return;
    }

    DUChainReadLocker lock;
    IndexedDeclaration decl = action->data().value<IndexedDeclaration>();
    if ( ! decl.isValid() ) {
        decl = Helper::declarationUnderCursor();
    }

    if ( ! decl.isValid() ) {
        qCWarning(KDEV_PYTHON_CODEGEN) << "No declaration found!";
        return;
    }

    CorrectionFileGenerator::HintType hintType;
    if ( decl.data()->isFunctionDeclaration() ) {
        hintType = CorrectionFileGenerator::FunctionReturnHint;
    }
    else if ( decl.data()->kind() == Declaration::Instance ) {
        hintType = CorrectionFileGenerator::LocalVariableHint;
    }
    else {
        qCWarning(KDEV_PYTHON_CODEGEN) << "Correction requested for something that's not a local variable or function.";
        return;
    }

    CorrectionAssistant *dialog = new CorrectionAssistant(decl, hintType);
    dialog->setAttribute(Qt::WA_DeleteOnClose);
    dialog->setWindowTitle(QStringLiteral("Specify type for ") + decl.data()->identifier().toString());
    connect(dialog, &QDialog::accepted, this, &TypeCorrection::accepted);

    m_ui->setupUi(dialog);
    connect(m_ui->buttonBox, &QDialogButtonBox::accepted, dialog, &QDialog::accept);
    connect(m_ui->buttonBox, &QDialogButtonBox::rejected, dialog, &QDialog::reject);
    if ( hintType == CorrectionFileGenerator::FunctionReturnHint ) {
        m_ui->kindLabel->setText(i18n("Function return type"));
    }
    else if ( hintType == CorrectionFileGenerator::LocalVariableHint ) {
        m_ui->kindLabel->setText(i18n("Local variable"));
    }

    m_ui->identifierLabel->setText(decl.data()->qualifiedIdentifier().toString());
    m_ui->typeText->setFocus();
    dialog->resize(560, 180);
    lock.unlock();

    dialog->show();
}

void TypeCorrection::accepted()
{
    CorrectionAssistant *dialog = qobject_cast<CorrectionAssistant*>(sender());
    Q_ASSERT(dialog);
    if ( ! dialog ) {
        qCWarning(KDEV_PYTHON_CODEGEN) << "accepted() called without a sender";
        return;
    }

    DUChainReadLocker lock;
    IndexedDeclaration decl;

    decl = dialog->declaration();

    if ( ! decl.isValid() ) {
        decl = Helper::declarationUnderCursor();
    }

    if ( ! decl.isValid() ) {
        qCWarning(KDEV_PYTHON_CODEGEN) << "No declaration found!";
        return;
    }

    auto correctionFile = Helper::getLocalCorrectionFile(decl.data()->topContext()->url().toUrl());
    if ( correctionFile.isEmpty() ) {
        KMessageBox::error(nullptr, i18n("Sorry, cannot create hints for files which are not part of a project."));
        return;
    }
    CorrectionFileGenerator generator(correctionFile.path());

    CorrectionFileGenerator::HintType hintType = dialog->hintType();

    generator.addHint(m_ui->typeText->text(), m_ui->importsText->text().split(QLatin1Char(','), Qt::SkipEmptyParts), decl.data(), hintType);

    qCDebug(KDEV_PYTHON_CODEGEN) << "Forcing a reparse on " << decl.data()->topContext()->url();
    ICore::self()->languageController()->backgroundParser()->addDocument(IndexedString(decl.data()->topContext()->url()),
                                                                         TopDUContext::ForceUpdate);
    ICore::self()->languageController()->backgroundParser()->addDocument(IndexedString(correctionFile),
                                                                         TopDUContext::ForceUpdate);
}

CorrectionFileGenerator::CorrectionFileGenerator(const QString &filePath)
    : m_file(filePath)
    , m_filePath(filePath)
{
    Q_ASSERT(! filePath.isEmpty());
    qCDebug(KDEV_PYTHON_CODEGEN) << "Correction file path: " << filePath;

    QFileInfo info(m_file);
    if ( ! info.absoluteDir().exists() ) {
        qCDebug(KDEV_PYTHON_CODEGEN) << "Directory does not exist. Creating...";
        info.absoluteDir().mkpath(info.absolutePath());
    }

    m_file.open(QFile::ReadWrite);

    m_code = QString::fromUtf8(m_file.readAll()).split(QLatin1Char('\n'));
    m_oldContents = m_code;
    m_fileIndents.reset(new FileIndentInformation(m_code));
}

void CorrectionFileGenerator::addHint(const QString &typeCode, const QStringList &modules, Declaration *forDeclaration,
                                      CorrectionFileGenerator::HintType hintType)
{
    if ( ! forDeclaration || ! forDeclaration->context() ) {
        qCWarning(KDEV_PYTHON_CODEGEN) << "Declaration does not have context!" << (forDeclaration ? forDeclaration->toString() : QString());
        return;
    }

    DUContext* context = forDeclaration->context();
    if ( context->type() == DUContext::Function ) {
        auto otherImporters = context->importers();
        if ( otherImporters.isEmpty() ) {
            return;
        }
        context = otherImporters.first();
    }

    // We're in a class if the context of the declaration is a Class or if its
    // parent context is a class. This is because a function body has a context
    // of type Other.
    bool inClass = context->type() == DUContext::Class
            || (context->parentContext() && context->parentContext()->type() == DUContext::Class);

    // If the declaration is part of the function's arguments or it's parent
    // context is one of a function.
    bool inFunction = context->type() == DUContext::Function
            || (context->owner() && context->owner()->abstractType()->whichType() == AbstractType::TypeFunction);

    qCDebug(KDEV_PYTHON_CODEGEN) << "Are we in a class: " << inClass;
    qCDebug(KDEV_PYTHON_CODEGEN) << "Are we in a function: " << inFunction;

    QString enclosingClassIdentifier, enclosingFunctionIdentifier;

    if ( context->owner() ) {
        if ( inClass && inFunction ) {
            Declaration *functionDeclaration = context->owner();

            enclosingClassIdentifier = functionDeclaration->context()->owner()->identifier().identifier().str();
            enclosingFunctionIdentifier = functionDeclaration->identifier().identifier().str();
        }
        else if ( inClass ) {
            enclosingClassIdentifier = context->owner()->identifier().identifier().str();
        }
        else if ( inFunction ) {
            enclosingFunctionIdentifier = context->owner()->identifier().identifier().str();
        }
    }

    qCDebug(KDEV_PYTHON_CODEGEN) << "Enclosing class: " << enclosingClassIdentifier;
    qCDebug(KDEV_PYTHON_CODEGEN) << "Enclosing function: " << enclosingFunctionIdentifier;

    QString declarationIdentifier = forDeclaration->identifier().identifier().str();

    bool foundClassDeclaration = false;
    bool foundFunctionDeclaration = false;

    QString functionIdentifier;

    if ( hintType == FunctionReturnHint ) {
        functionIdentifier = declarationIdentifier;
    }
    else if ( hintType == LocalVariableHint ) {
        functionIdentifier = enclosingFunctionIdentifier;
    }

    int line = findStructureFor(enclosingClassIdentifier, functionIdentifier);

    if ( line == -1 ) {
        line = findStructureFor(enclosingClassIdentifier, QString());
    }
    else if ( inFunction || hintType == FunctionReturnHint ) {
        foundFunctionDeclaration = true;
    }

    if ( line == -1 ) {
        line = findStructureFor(QString(), QString());
    }
    else if ( inClass ) {
        foundClassDeclaration = true;
    }

    qCDebug(KDEV_PYTHON_CODEGEN) << "Found class declaration: " << foundClassDeclaration << enclosingClassIdentifier;
    qCDebug(KDEV_PYTHON_CODEGEN) << "Found function declaration: " << foundFunctionDeclaration << functionIdentifier;
    qCDebug(KDEV_PYTHON_CODEGEN) << "Line: " << line;

    int indentsForNextStatement = m_fileIndents->indentForLine(line);

    if ( foundClassDeclaration ) {
        indentsForNextStatement += DEFAULT_INDENT_LEVEL;
    }

    QStringList newCode;
    if ( inClass ) {
        if ( ! foundClassDeclaration ) {
            QString classDeclaration = createStructurePart(enclosingClassIdentifier, ClassType);
            classDeclaration.prepend(QString(indentsForNextStatement, QLatin1Char(' ')));

            newCode.append(classDeclaration);
            indentsForNextStatement += DEFAULT_INDENT_LEVEL;
        }
        else {
            line++;
        }
    }

    if ( inFunction || hintType == FunctionReturnHint ) {
        if ( ! foundFunctionDeclaration ) {
            QString functionDeclaration;
            if ( inClass ) {
                functionDeclaration = createStructurePart(functionIdentifier, MemberFunctionType);
            }
            else {
                functionDeclaration = createStructurePart(functionIdentifier, FunctionType);
            }
            functionDeclaration.prepend(QString(indentsForNextStatement, QLatin1Char(' ')));

            newCode.append(functionDeclaration);
            indentsForNextStatement += DEFAULT_INDENT_LEVEL;
        }
        else {
            line++;
        }
    }

    if ( foundFunctionDeclaration && ! foundClassDeclaration ) {
        indentsForNextStatement += DEFAULT_INDENT_LEVEL;
    }
    QString hintCode;
    if ( hintType == FunctionReturnHint ) {
        hintCode = QStringLiteral("returns = ") + typeCode;
    }
    else if ( hintType == LocalVariableHint ) {
        hintCode = QStringLiteral("l_") + declarationIdentifier + QStringLiteral(" = ") + typeCode;
    }
    qCDebug(KDEV_PYTHON_CODEGEN) << "Hint code: " << hintCode;
    hintCode.prepend(QString(indentsForNextStatement, QLatin1Char(' ')));
    newCode.append(hintCode);

    for ( int i = 0; i < newCode.length(); i++ ) {
        m_code.insert(line + i, newCode.at(i));
    }

    // We safely insert any import declaration at the top
    for ( const QString &moduleName : modules ) {
        bool importExists = false;
        for (const QString& line : std::as_const(m_code)) {
            if ( ! line.startsWith(QStringLiteral("import")) && ! line.startsWith(QStringLiteral("from")) && ! line.isEmpty() ) {
                break;
            }

            // In both import ... and from ... import ..., the second part is what we want
            if ( line.section(QLatin1Char(' '), 1, 1, QString::SectionSkipEmpty) == moduleName.trimmed() ) {
                importExists = true;
            }
        }

        if ( ! importExists ) {
            m_code.prepend(QStringLiteral("import ") + moduleName.trimmed());
        }
    }

    QTemporaryFile temp;
    if ( checkForValidSyntax() && temp.open() ) {
        qCDebug(KDEV_PYTHON_CODEGEN) << "File path: " << m_file.fileName();
        qCDebug(KDEV_PYTHON_CODEGEN) << "Temporary file path: " << temp.fileName();
        QTextStream stream(&temp);
        stream << m_code.join(QLatin1Char('\n'));
        m_fileIndents.reset(new FileIndentInformation(m_code));
        stream.flush();

        bool success = m_file.remove();
        success = success ? QFile::rename(temp.fileName(), m_file.fileName()) : false;

        if ( success && m_file.open(QFile::ReadWrite) ) {
            qCDebug(KDEV_PYTHON_CODEGEN) << "Successfully saved correction file.";

            m_oldContents = m_code;
        }
        else {
            m_code = m_oldContents;
        }
    }
    else {
        qCDebug(KDEV_PYTHON_CODEGEN) << "Something went wrong, reverting changes to correction file";
        m_code = m_oldContents;
    }
}

class StructureFindVisitor : public Python::AstDefaultVisitor
{
public:
    StructureFindVisitor(const QString &klass, const QString &function)
        : m_line(-1)
    {
        if ( ! klass.isNull() ) {
            m_searchedDeclaration.push(klass);
        }

        if ( ! function.isNull() ) {
            m_searchedDeclaration.push(function);
        }
    }

    void visitFunctionDefinition(FunctionDefinitionAst* node) override
    {
        m_declaration.push(node->name->value);

        if ( m_declaration == m_searchedDeclaration ) {
            m_line = node->startLine;
        }

        AstDefaultVisitor::visitFunctionDefinition(node);

        m_declaration.pop();
    }

    void visitClassDefinition(ClassDefinitionAst* node) override
    {
        m_declaration.push(node->name->value);

        if ( m_declaration == m_searchedDeclaration ) {
            m_line = node->startLine;
        }

        AstDefaultVisitor::visitClassDefinition(node);

        m_declaration.pop();
    }

    int line() const
    {
        return m_line;
    }

private:
    QStack<QString> m_searchedDeclaration;
    QStack<QString> m_declaration;
    int m_line;
};

int CorrectionFileGenerator::findStructureFor(const QString &klass, const QString &function)
{
    // If we're not looking for a specific thing, return the end of the file
    if ( klass.isNull() && function.isNull() ) {
        return m_code.length() - 1;
    }

    ParseSession parseSession;
    parseSession.setContents(m_code.join(QLatin1Char('\n')));
    parseSession.setCurrentDocument(IndexedString(m_filePath));

    QPair<CodeAst::Ptr, bool> parsed = parseSession.parse();

    QString classIdentifier = ( ! klass.isNull() ) ? QStringLiteral("class_") + klass : QString();
    QString functionIdentifier = ( ! function.isNull() ) ? QStringLiteral("function_") + function : QString();

    StructureFindVisitor visitor(classIdentifier, functionIdentifier);
    visitor.visitCode(parsed.first.data());

    return visitor.line();
}

QString CorrectionFileGenerator::createStructurePart(const QString &identifierSuffix, CorrectionFileGenerator::StructureType type)
{
    QString code;
    QString params;

    switch ( type ) {
    case ClassType:
        code = QStringLiteral("class class_") + identifierSuffix + QLatin1Char(':');
        break;
    case MemberFunctionType:
        params = QStringLiteral("self");
        // Fall through
    case FunctionType:
        code = QStringLiteral("def function_") + identifierSuffix + QLatin1Char('(') + params + QStringLiteral("):");
        break;
    }

    return code;
}

bool CorrectionFileGenerator::checkForValidSyntax()
{
    ParseSession parseSession;
    parseSession.setContents(m_code.join(QLatin1Char('\n')));
    parseSession.setCurrentDocument(IndexedString(m_filePath));

    QPair<CodeAst::Ptr, bool> parsed = parseSession.parse();

    return parsed.second && parseSession.m_problems.isEmpty();
}

CorrectionAssistant::CorrectionAssistant(IndexedDeclaration declaration, CorrectionFileGenerator::HintType hintType,
                                         QWidget *parent)
    : QDialog(parent),
      m_declaration(declaration),
      m_hintType(hintType)
{
}

IndexedDeclaration CorrectionAssistant::declaration() const
{
    return m_declaration;
}

CorrectionFileGenerator::HintType CorrectionAssistant::hintType() const
{
    return m_hintType;
}

}

#include "moc_correctionfilegenerator.cpp"