File: helper.cpp

package info (click to toggle)
kdevelop-php 22.12.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 8,536 kB
  • sloc: cpp: 20,182; php: 15,243; xml: 114; sh: 58; makefile: 9
file content (593 lines) | stat: -rw-r--r-- 22,635 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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
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
/*
    SPDX-FileCopyrightText: 2008 Niko Sams <niko.sams@gmail.com>

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

#include "helper.h"

#include <KParts/MainWindow>
#include <KLocalizedString>

#include <language/duchain/ducontext.h>
#include <language/duchain/duchainlock.h>
#include <language/duchain/persistentsymboltable.h>
#include <language/duchain/duchain.h>
#include <language/duchain/stringhelpers.h>
#include <language/duchain/parsingenvironment.h>
#include <language/duchain/types/unsuretype.h>
#include <language/duchain/types/integraltype.h>
#include <language/duchain/types/arraytype.h>
#include <interfaces/icore.h>
#include <interfaces/iprojectcontroller.h>
#include <interfaces/iuicontroller.h>
#include <interfaces/iproject.h>
#include <project/projectmodel.h>
#include <util/path.h>

#include "editorintegrator.h"
#include "../parser/parsesession.h"
#include "phpast.h"
#include "phpdefaultvisitor.h"
#include "declarations/classdeclaration.h"
#include "declarations/classmethoddeclaration.h"
#include "declarations/functiondeclaration.h"
#include "types/integraltypeextended.h"
#include "expressionparser.h"
#include "expressionvisitor.h"

#include "duchaindebug.h"

#define ifDebug(x)

using namespace KDevelop;

namespace Php
{

bool isMatch(Declaration* declaration, DeclarationType declarationType)
{
    if (declarationType == ClassDeclarationType
            && dynamic_cast<ClassDeclaration*>(declaration)
       ) {
        return true;
    } else if (declarationType == FunctionDeclarationType
               && dynamic_cast<FunctionDeclaration*>(declaration)
              ) {
        return true;
    } else if (declarationType == ConstantDeclarationType
               && declaration->abstractType() && declaration->abstractType()->modifiers() & AbstractType::ConstModifier
               && (!declaration->context() || declaration->context()->type() != DUContext::Class)
              ) {
        return true;
    } else if (declarationType == GlobalVariableDeclarationType
               && declaration->kind() == Declaration::Instance
               && !(declaration->abstractType() && declaration->abstractType()->modifiers() & AbstractType::ConstModifier)
              ) {
        return true;
    } else if (declarationType == NamespaceDeclarationType
               && (declaration->kind() == Declaration::Namespace || declaration->kind() == Declaration::NamespaceAlias || dynamic_cast<ClassDeclaration*>(declaration)) )
    {
        return true;
    }
    return false;
}

bool isGenericClassTypehint(NamespacedIdentifierAst* node, EditorIntegrator *editor)
{
    const KDevPG::ListNode< IdentifierAst* >* it = node->namespaceNameSequence->front();
    QString typehint = editor->parseSession()->symbol(it->element);

    if (typehint.compare(QLatin1String("bool"), Qt::CaseInsensitive) == 0) {
        return false;
    } else if (typehint.compare(QLatin1String("float"), Qt::CaseInsensitive) == 0) {
        return false;
    } else if (typehint.compare(QLatin1String("int"), Qt::CaseInsensitive) == 0) {
        return false;
    } else if (typehint.compare(QLatin1String("string"), Qt::CaseInsensitive) == 0) {
        return false;
    } else if (typehint.compare(QLatin1String("iterable"), Qt::CaseInsensitive) == 0) {
        return false;
    } else if (typehint.compare(QLatin1String("object"), Qt::CaseInsensitive) == 0) {
        return false;
    } else {
        return true;
    }
}

bool isClassTypehint(GenericTypeHintAst* genericType, EditorIntegrator *editor)
{
    Q_ASSERT(genericType);

    if (genericType->callableType != -1) {
        return false;
    } else if (genericType->arrayType != -1) {
        return false;
    } else if (genericType->genericType) {
        return isGenericClassTypehint(genericType->genericType, editor);
    } else {
        return false;
    }
}

bool isClassTypehint(PropertyTypeHintAst* propertyType, EditorIntegrator *editor)
{
    Q_ASSERT(propertyType);

    if (propertyType->arrayType != -1) {
        return false;
    } else if (propertyType->genericType) {
        return isGenericClassTypehint(propertyType->genericType, editor);
    } else {
        return false;
    }
}

DeclarationPointer findDeclarationImportHelper(DUContext* currentContext, const QualifiedIdentifier& id,
        DeclarationType declarationType)
{
    /// Qualified identifier for 'self'
    static const QualifiedIdentifier selfQId(QStringLiteral("self"));
    /// Qualified identifier for 'parent'
    static const QualifiedIdentifier parentQId(QStringLiteral("parent"));
    /// Qualified identifier for 'static'
    static const QualifiedIdentifier staticQId(QStringLiteral("static"));

    QualifiedIdentifier lookup;

    if (id.explicitlyGlobal()) {
        ifDebug(qCDebug(DUCHAIN) << id.toString() << declarationType;)

        lookup = id;
        lookup.setExplicitlyGlobal(false);
    } else {
        lookup = identifierWithNamespace(id, currentContext);

        ifDebug(qCDebug(DUCHAIN) << lookup.toString() << declarationType;)
    }

    if (declarationType == ClassDeclarationType && id == selfQId) {
        DUChainReadLocker lock(DUChain::lock());
        if (currentContext->type() == DUContext::Class) {
            return DeclarationPointer(currentContext->owner());
        } else if (currentContext->parentContext() && currentContext->parentContext()->type() == DUContext::Class) {
            return DeclarationPointer(currentContext->parentContext()->owner());
        } else {
            return DeclarationPointer();
        }
    } else if (declarationType == ClassDeclarationType && id == staticQId) {
        DUChainReadLocker lock;
        if (currentContext->type() == DUContext::Class) {
            return DeclarationPointer(currentContext->owner());
        } else if (currentContext->parentContext() && currentContext->parentContext()->type() == DUContext::Class) {
            return DeclarationPointer(currentContext->parentContext()->owner());
        } else {
            return DeclarationPointer();
        }
    } else if (declarationType == ClassDeclarationType && id == parentQId) {
        //there can be just one Class-Context imported
        DUChainReadLocker lock;
        DUContext* classCtx = nullptr;
        if (currentContext->type() == DUContext::Class) {
            classCtx = currentContext;
        } else if (currentContext->parentContext() && currentContext->parentContext()->type() == DUContext::Class) {
            classCtx = currentContext->parentContext();
        }
        if (classCtx) {
            foreach(const DUContext::Import &i, classCtx->importedParentContexts()) {
                DUContext* ctx = i.context(classCtx->topContext());
                if (ctx && ctx->type() == DUContext::Class) {
                    return DeclarationPointer(ctx->owner());
                }
            }
        }
        return DeclarationPointer();
    } else {
        DUChainReadLocker lock;
        QList<Declaration*> foundDeclarations = currentContext->topContext()->findDeclarations(lookup);

        foreach(Declaration *declaration, foundDeclarations) {
            if (isMatch(declaration, declarationType)) {
                return DeclarationPointer(declaration);
            }
        }
        if ( currentContext->url() == internalFunctionFile() ) {
            // when compiling php internal functions, we don't need to ask the persistent symbol table for anything
            return DeclarationPointer();
        }

        lock.unlock();

        if (declarationType != GlobalVariableDeclarationType) {
            ifDebug(qCDebug(DUCHAIN) << "No declarations found with findDeclarations, trying through PersistentSymbolTable";)
            DeclarationPointer decl;

            decl = findDeclarationInPST(currentContext, lookup, declarationType);

            if (decl) {
                ifDebug(qCDebug(DUCHAIN) << "PST declaration exists";)
            } else {
                ifDebug(qCDebug(DUCHAIN) << "PST declaration does not exist";)
            }
            return decl;
        }
    }

    ifDebug(qCDebug(DUCHAIN) << "returning 0";)
    return DeclarationPointer();
}

DeclarationPointer findDeclarationInPST(DUContext* currentContext, QualifiedIdentifier id, DeclarationType declarationType)
{
    DeclarationPointer ret;

    ifDebug(qCDebug(DUCHAIN) << "PST: " << id.toString() << declarationType;)
    DUChainWriteLocker wlock;

    /// Indexed string for 'Php', identifies environment files from this language plugin
    static const IndexedString phpLangString("Php");
    auto visitor = [&](const IndexedDeclaration &indexedDeclaration) {
        ParsingEnvironmentFilePointer env = DUChain::self()->environmentFileForDocument(indexedDeclaration.indexedTopContext());
        if(!env) {
            ifDebug(qCDebug(DUCHAIN) << "skipping declaration, missing meta-data";)
            return PersistentSymbolTable::VisitorState::Continue;
        }
        if(env->language() != phpLangString) {
            ifDebug(qCDebug(DUCHAIN) << "skipping declaration, invalid language" << env->language().str();)
            return PersistentSymbolTable::VisitorState::Continue;
        }

        const auto declaration = indexedDeclaration.declaration();
        if (!declaration) {
            ifDebug(qCDebug(DUCHAIN) << "skipping declaration, doesn't have declaration";)
            return PersistentSymbolTable::VisitorState::Continue;
        } else if (!isMatch(declaration, declarationType)) {
            ifDebug(qCDebug(DUCHAIN) << "skipping declaration, doesn't match with declarationType";)
            return PersistentSymbolTable::VisitorState::Continue;
        }

        TopDUContext* top = declaration->context()->topContext();
        currentContext->topContext()->addImportedParentContext(top);
        currentContext->topContext()->parsingEnvironmentFile()
        ->addModificationRevisions(top->parsingEnvironmentFile()->allModificationRevisions());
        currentContext->topContext()->updateImportsCache();
        ifDebug(qCDebug(DUCHAIN) << "using" << declarations[i].declaration()->toString() << top->url();)
        ret = declaration;
        return PersistentSymbolTable::VisitorState::Break;
    };
    PersistentSymbolTable::self().visitDeclarations(id, visitor);

    return ret;
}

QByteArray formatComment(AstNode* node, EditorIntegrator* editor)
{
    return KDevelop::formatComment(editor->parseSession()->docComment(node->startToken).toUtf8());
}

//Helper visitor to extract a commonScalar node
//used to get the value of an function call argument
class ScalarExpressionVisitor : public DefaultVisitor
{
public:
    ScalarExpressionVisitor() : m_node(nullptr) {}
    CommonScalarAst* node() const {
        return m_node;
    }
private:
    void visitCommonScalar(CommonScalarAst* node) override {
        m_node = node;
    }
    CommonScalarAst* m_node;
};

CommonScalarAst* findCommonScalar(AstNode* node)
{
    ScalarExpressionVisitor visitor;
    visitor.visitNode(node);
    return visitor.node();
}

static bool includeExists(const Path &include)
{
    const QString path = include.pathOrUrl();
    {
        DUChainReadLocker lock;
        if (DUChain::self()->chainForDocument(IndexedString(path))) {
            return true;
        }
    }
    if ( include.isLocalFile() ) {
        return QFile::exists(path);
    } else {
        return false;
    }
}

static IndexedString findIncludeFile(const QString &includePath, const IndexedString &currentDocument)
{
    if ( includePath.isEmpty() ) {
        return IndexedString();
    }

    // check remote files
    if ( includePath.startsWith(QLatin1String("http://"), Qt::CaseInsensitive)
            || includePath.startsWith(QLatin1String("ftp://"), Qt::CaseInsensitive) ) {
        // always expect remote includes to exist
        return IndexedString(includePath);
    }

    const Path currentPath(currentDocument.str());

    // look for file relative to current url
    Path include = Path(currentPath.parent(), includePath);
    if ( includeExists(include) ) {
        return IndexedString(include.pathOrUrl());
    }

    // in the first round look for a project that is a parent of the current document
    // in the next round look for any project
    for (int i = 0; i < 2; ++i) {
        foreach(IProject* project, ICore::self()->projectController()->projects()) {
            if ( !i && !project->path().isParentOf(currentPath)) {
                continue;
            }
            include = Path(project->path(), includePath);
            if ( includeExists(include) ) {
                return IndexedString(include.pathOrUrl());
            }
        }
    }

    //TODO configurable include paths

    return IndexedString();
}

IndexedString getIncludeFileForNode(UnaryExpressionAst* node, EditorIntegrator* editor) {
    if ( node->includeExpression ) {
        //find name of the constant (first argument of the function call)
        CommonScalarAst* scalar = findCommonScalar(node->includeExpression);
        if (scalar && scalar->string != -1) {
            QString str = editor->parseSession()->symbol(scalar->string);
            str = str.mid(1, str.length() - 2);
            if ( str == QLatin1String(".") || str == QLatin1String("..") || str.endsWith('/') ) {
                return IndexedString();
            }
            return findIncludeFile(str, editor->parseSession()->currentDocument());
        }
    }

    return IndexedString();
}

QString prettyName(Declaration* dec) {
    if (!dec) {
        return {};
    } else if ( dec->context() && dec->context()->type() == DUContext::Class && dec->isFunctionDeclaration() ) {
        ClassMethodDeclaration* classMember = dynamic_cast<ClassMethodDeclaration*>(dec);
        Q_ASSERT(classMember);
        return classMember->prettyName().str();
    } else if ( dec->isFunctionDeclaration() ) {
        FunctionDeclaration* func = dynamic_cast<FunctionDeclaration*>(dec);
        Q_ASSERT(func);
        return func->prettyName().str();
    } else if ( dec->internalContext() && dec->internalContext()->type() == DUContext::Class ) {
        ClassDeclaration* classDec = dynamic_cast<ClassDeclaration*>(dec);
        Q_ASSERT(classDec);
        return classDec->prettyName().str();
    } else {
        return dec->identifier().toString();
    }
}

const KDevelop::IndexedString& internalFunctionFile()
{
    static const KDevelop::IndexedString internalFile(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("kdevphpsupport/phpfunctions.php")));
    return internalFile;
}

const KDevelop::IndexedString& phpLanguageString()
{
    static const KDevelop::IndexedString phpLangString("Php");
    return phpLangString;
}

const IndexedString& internalTestFile()
{
    static const KDevelop::IndexedString phpUnitFile(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("kdevphpsupport/phpunitdeclarations.php")));
    return phpUnitFile;
}

QualifiedIdentifier identifierForNamespace(NamespacedIdentifierAst* node, EditorIntegrator* editor, bool lastIsConstIdentifier)
{
    QualifiedIdentifier id;
    if (node->isGlobal != -1) {
        id.setExplicitlyGlobal(true);
    }
    const KDevPG::ListNode< IdentifierAst* >* it = node->namespaceNameSequence->front();
    do {
        if (lastIsConstIdentifier && !it->hasNext()) {
            id.push(Identifier(editor->parseSession()->symbol(it->element)));
        } else {
            id.push(Identifier(editor->parseSession()->symbol(it->element).toLower()));
        }
    } while (it->hasNext() && (it = it->next));
    return id;
}

QualifiedIdentifier identifierWithNamespace(const QualifiedIdentifier& base, DUContext* context)
{
    DUChainReadLocker lock;
    auto scope = context;
    while (scope && scope->type() != DUContext::Namespace) {
        scope = scope->parentContext();
    }

    if (scope) {
        return scope->scopeIdentifier() + base;
    } else {
        return base;
    }
}

template <class T>
AbstractType::Ptr determineTypehint(const T* genericType, EditorIntegrator *editor, DUContext* currentContext)
{
    Q_ASSERT(genericType);
    AbstractType::Ptr type;

    if (genericType->typehint) {
        if (genericType->typehint->callableType != -1) {
            type = AbstractType::Ptr(new IntegralTypeExtended(IntegralTypeExtended::TypeCallable));
        } else if (genericType->typehint->arrayType != -1) {
            type = AbstractType::Ptr(new IntegralType(IntegralType::TypeArray));
        } else if (genericType->typehint->genericType) {
            NamespacedIdentifierAst* node = genericType->typehint->genericType;
            const KDevPG::ListNode< IdentifierAst* >* it = node->namespaceNameSequence->front();
            QString typehint = editor->parseSession()->symbol(it->element);

            if (typehint.compare(QLatin1String("bool"), Qt::CaseInsensitive) == 0) {
                type = AbstractType::Ptr(new IntegralType(IntegralType::TypeBoolean));
            } else if (typehint.compare(QLatin1String("float"), Qt::CaseInsensitive) == 0) {
                type = AbstractType::Ptr(new IntegralType(IntegralType::TypeFloat));
            } else if (typehint.compare(QLatin1String("int"), Qt::CaseInsensitive) == 0) {
                type = AbstractType::Ptr(new IntegralType(IntegralType::TypeInt));
            } else if (typehint.compare(QLatin1String("string"), Qt::CaseInsensitive) == 0) {
                type = AbstractType::Ptr(new IntegralType(IntegralType::TypeString));
            } else if (typehint.compare(QLatin1String("object"), Qt::CaseInsensitive) == 0) {
                type = AbstractType::Ptr(new IntegralTypeExtended(IntegralTypeExtended::TypeObject));
            } else if (typehint.compare(QLatin1String("iterable"), Qt::CaseInsensitive) == 0) {
                DeclarationPointer traversableDecl = findDeclarationImportHelper(currentContext, QualifiedIdentifier(u"traversable"), ClassDeclarationType);

                if (traversableDecl) {
                    UnsureType::Ptr unsure(new UnsureType());
                    AbstractType::Ptr arrayType = AbstractType::Ptr(new IntegralType(IntegralType::TypeArray));
                    unsure->addType(arrayType->indexed());
                    unsure->addType(traversableDecl->abstractType()->indexed());

                    type = AbstractType::Ptr(unsure);
                }
            } else {
                //don't use openTypeFromName as it uses cursor for findDeclarations
                DeclarationPointer decl = findDeclarationImportHelper(currentContext,
                                                            identifierForNamespace(genericType->typehint->genericType, editor), ClassDeclarationType);
                if (decl) {
                    type = decl->abstractType();
                }
            }
        }
    }

    if (type && genericType->isNullable != -1) {
        AbstractType::Ptr nullType = AbstractType::Ptr(new IntegralType(IntegralType::TypeNull));
        if (type.cast<UnsureType>()) {
            UnsureType::Ptr unsure = type.cast<UnsureType>();
            unsure->addType(nullType->indexed());
        } else {
            UnsureType::Ptr unsure(new UnsureType());
            unsure->addType(type->indexed());
            unsure->addType(nullType->indexed());

            type = AbstractType::Ptr(unsure);
        }
    }

    return type;
}

AbstractType::Ptr parameterType(const ParameterAst* node, AbstractType::Ptr phpDocTypehint, EditorIntegrator* editor, DUContext* currentContext)
{
    AbstractType::Ptr type;
    if (node->parameterType) {
        type = determineTypehint(node->parameterType, editor, currentContext);
    }
    if (node->defaultValue) {
        ExpressionVisitor v(editor);
        node->defaultValue->ducontext = currentContext;
        v.visitNode(node->defaultValue);
        AbstractType::Ptr defaultValueType = v.result().type();

        /*
         * If a typehint is already set, default values can only be the same type or `null` in PHP
         * If it's the same type, the type is already correctly set,
         *    so we can ignore this case.
         * If it's null (which cannot be a typehint), add it as UnsureType
         */
        if (type && defaultValueType.cast<IntegralType>() && defaultValueType.cast<IntegralType>()->dataType() == IntegralType::TypeNull) {
            if (type.cast<UnsureType>()) {
                UnsureType::Ptr unsure = type.cast<UnsureType>();
                AbstractType::Ptr nullType = AbstractType::Ptr(new IntegralType(IntegralType::TypeNull));
                unsure->addType(defaultValueType->indexed());
            } else {
                UnsureType::Ptr unsure(new UnsureType());
                unsure->addType(type->indexed());
                unsure->addType(defaultValueType->indexed());

                type = AbstractType::Ptr(unsure);
            }
        } else {
            //Otherwise, let the default value dictate the parameter type
            type = defaultValueType;
        }
    }
    if (!type) {
        if (phpDocTypehint) {
            type = phpDocTypehint;
        } else {
            type = AbstractType::Ptr(new IntegralType(IntegralType::TypeMixed));
        }
    }

    if ( node->isRef != -1 ) {
      ReferenceType::Ptr p( new ReferenceType() );
      p->setBaseType( type );

      type = p.cast<AbstractType>();
    }

    if (node->isVariadic != -1) {
        auto *container = new KDevelop::ArrayType();
        container->setElementType(type);
        type = AbstractType::Ptr(container);
    }

    Q_ASSERT(type);
    return type;
}

AbstractType::Ptr propertyType(const ClassStatementAst* node, AbstractType::Ptr phpDocTypehint, EditorIntegrator* editor, DUContext* currentContext)
{
    AbstractType::Ptr type;
    if (node->propertyType) {
        type = determineTypehint(node->propertyType, editor, currentContext);
    }

    if (!type) {
        if (phpDocTypehint) {
            type = phpDocTypehint;
        } else {
            type = AbstractType::Ptr(new IntegralType(IntegralType::TypeMixed));
        }
    }

    Q_ASSERT(type);
    return type;
}

AbstractType::Ptr returnType(const ReturnTypeAst* node, AbstractType::Ptr phpDocTypehint, EditorIntegrator* editor, DUContext* currentContext) {
    AbstractType::Ptr type;
    if (node) {
        if (node->voidType != -1) {
            type = AbstractType::Ptr(new IntegralType(IntegralType::TypeVoid));
        } else {
            type = determineTypehint(node, editor, currentContext);
        }
    }
    if (!type) {
        type = phpDocTypehint;
    }
    return type;
}

}