aboutsummaryrefslogtreecommitdiffstats
path: root/src/qmlcompiler/qqmlsa.cpp
blob: 0b6e88ef7c4c1c5077595596f9a8a1abe4affd4d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "qqmlsa_p.h"

#include "qqmljsscope_p.h"
#include "qqmljslogger_p.h"
#include "qqmljstyperesolver_p.h"
#include "qqmljsimportvisitor_p.h"
#include "qqmljsutils_p.h"

#include <memory>

QT_BEGIN_NAMESPACE

using namespace Qt::StringLiterals;

namespace QQmlSA {

class GenericPassPrivate {
public:
    const PassManager *manager;
};

GenericPass::~GenericPass() = default;

GenericPass::GenericPass(PassManager *manager)
{
    Q_ASSERT(manager);
    d = std::make_unique<GenericPassPrivate>();
    d->manager = manager;
}

void GenericPass::emitWarning(QAnyStringView message, LoggerWarningId id,
                              QQmlJS::SourceLocation srcLocation)
{
    d->manager->m_visitor->logger()->log(message.toString(), id, srcLocation);
}

Element GenericPass::resolveType(QAnyStringView moduleName, QAnyStringView typeName)
{
    auto typeImporter = d->manager->m_visitor->importer();
    auto module = typeImporter->importModule(moduleName.toString());
    return module.type(typeName.toString()).scope;
}

Element GenericPass::resolveLiteralType(const QQmlJSMetaPropertyBinding &binding)
{
    return binding.literalType(d->manager->m_typeResolver);
}

/*!
 * \brief PassManager::registerElementPass registers ElementPass
          with the pass manager.
   \param pass The registered pass. Ownership is transferred to the pass manager.
 */
void PassManager::registerElementPass(std::unique_ptr<ElementPass> pass)
{
    m_elementPasses.push_back(std::move(pass));
}

enum LookupMode { Register, Lookup };
static QString lookupName(const QQmlSA::Element &element, LookupMode mode = Lookup)
{
    QString name;
    if (element.isNull() || element->internalName().isEmpty()) {
        // Bail out with an invalid name, this type is so screwed up we can't do anything reasonable
        // with it We should have warned about it in another plac
        if (element.isNull() || element->baseType().isNull())
            return u"$INVALID$"_s;
        name = element->baseType()->internalName();
    } else {
        name = element->internalName();
    }

    const QString filePath =
            (mode == Register || !element->baseType() ? element : element->baseType())->filePath();

    if (element->isComposite() && !filePath.endsWith(u".h"))
        name += u'@' + filePath;
    return name;
}

bool PassManager::registerPropertyPass(std::shared_ptr<PropertyPass> pass,
                                       QAnyStringView moduleName, QAnyStringView typeName,
                                       QAnyStringView propertyName, bool allowInheritance)
{
    QString name;
    if (!moduleName.isEmpty() && !typeName.isEmpty()) {
        auto typeImporter = m_visitor->importer();
        auto module = typeImporter->importModule(moduleName.toString());
        auto element = module.type(typeName.toString()).scope;

        if (element.isNull())
            return false;

        name = lookupName(element, Register);
    }
    const PassManager::PropertyPassInfo passInfo {
        propertyName.isEmpty() ? QStringList {} : QStringList { propertyName.toString() },
        std::move(pass), allowInheritance
    };
    m_propertyPasses.insert({ name, passInfo });

    return true;
}

void PassManager::addBindingSourceLocations(const Element &element, const Element &scope,
                                            const QString prefix, bool isAttached)
{
    const Element &currentScope = scope.isNull() ? element : scope;
    const auto ownBindings = currentScope->ownPropertyBindings();
    for (const auto &binding : ownBindings.values()) {
        switch (binding.bindingType()) {
        case QQmlJSMetaPropertyBinding::GroupProperty:
            addBindingSourceLocations(element, binding.groupType(),
                                      prefix + binding.propertyName() + u'.');
            break;
        case QQmlJSMetaPropertyBinding::AttachedProperty:
            addBindingSourceLocations(element, binding.attachingType(),
                                      prefix + binding.propertyName() + u'.', true);
            break;
        default:
            m_bindingsByLocation.insert({ binding.sourceLocation().offset,
                                          BindingInfo { prefix + binding.propertyName(), binding,
                                                        currentScope, isAttached } });

            if (binding.bindingType() != QQmlJSMetaPropertyBinding::Script)
                analyzeBinding(element, QQmlSA::Element(), binding.sourceLocation());
        }
    }
}

void PassManager::analyze(const Element &root)
{
    QList<Element> runStack;
    runStack.push_back(root);
    while (!runStack.isEmpty()) {
        auto element = runStack.takeLast();
        addBindingSourceLocations(element);
        for (auto &elementPass : m_elementPasses)
            if (elementPass->shouldRun(element))
                elementPass->run(element);
        const auto ownPropertyBindings = element->ownPropertyBindings();

        for (auto it = element->childScopesBegin(); it != element->childScopesEnd(); ++it) {
            if ((*it)->scopeType() == QQmlJSScope::QMLScope)
                runStack.push_back(*it);
        }
    }
}

void PassManager::analyzeWrite(const Element &element, QString propertyName, const Element &value,
                               const Element &writeScope, QQmlJS::SourceLocation location)
{
    for (PropertyPass *pass : findPropertyUsePasses(element, propertyName))
        pass->onWrite(element, propertyName, value, writeScope, location);
}

void PassManager::analyzeRead(const Element &element, QString propertyName,
                              const Element &readScope, QQmlJS::SourceLocation location)
{
    for (PropertyPass *pass : findPropertyUsePasses(element, propertyName))
        pass->onRead(element, propertyName, readScope, location);
}

void PassManager::analyzeBinding(const Element &element, const QQmlSA::Element &value,
                                 QQmlJS::SourceLocation location)
{
    const auto info = m_bindingsByLocation.find(location.offset);

    // If there's no matching binding that means we're in a nested Ret somewhere inside an
    // expression
    if (info == m_bindingsByLocation.end())
        return;

    const QQmlSA::Element &bindingScope = info->second.bindingScope;
    const QQmlJSMetaPropertyBinding &binding = info->second.binding;
    const QString &propertyName = info->second.fullPropertyName;

    for (PropertyPass *pass : findPropertyUsePasses(element, propertyName))
        pass->onBinding(element, propertyName, binding, bindingScope, value);

    if (!info->second.isAttached || bindingScope->baseType().isNull())
        return;

    for (PropertyPass *pass : findPropertyUsePasses(bindingScope->baseType(), propertyName))
        pass->onBinding(element, propertyName, binding, bindingScope, value);
}

bool PassManager::hasImportedModule(QAnyStringView module) const
{
    return m_visitor->imports().hasType(u"$module$." + module.toString());
}

QSet<PropertyPass *> PassManager::findPropertyUsePasses(const QQmlSA::Element &element,
                                                        const QString &propertyName)
{
    QStringList typeNames { lookupName(element) };

    QQmlJSUtils::searchBaseAndExtensionTypes(
            element, [&](const QQmlJSScope::ConstPtr &scope, QQmlJSScope::ExtensionKind mode) {
                Q_UNUSED(mode);
                typeNames.append(lookupName(scope));
                return false;
            });

    QSet<PropertyPass *> passes;

    for (const QString &typeName : typeNames) {
        for (auto &pass :
             { m_propertyPasses.equal_range(u""_s), m_propertyPasses.equal_range(typeName) }) {
            if (pass.first == pass.second)
                continue;

            for (auto it = pass.first; it != pass.second; it++) {
                if (typeName != typeNames.constFirst() && !it->second.allowInheritance)
                    continue;
                if (it->second.properties.isEmpty()
                    || it->second.properties.contains(propertyName)) {
                    passes.insert(it->second.pass.get());
                }
            }
        }
    }
    return passes;
}

void DebugElementPass::run(const Element &element) {
    emitWarning(u"Type: " + element->baseTypeName(), qmlPlugin);
    if (auto bindings = element->propertyBindings(u"objectName"_s); !bindings.isEmpty()) {
        emitWarning(u"is named: " + bindings.first().stringValue(), qmlPlugin);
    }
    if (auto defPropName = element->defaultPropertyName(); !defPropName.isEmpty()) {
        emitWarning(u"binding " + QString::number(element->propertyBindings(defPropName).size())
                            + u" elements to property "_s + defPropName,
                    qmlPlugin);
    }
}

bool ElementPass::shouldRun(const Element &)
{
    return true;
}

PropertyPass::PropertyPass(PassManager *manager) : GenericPass(manager) { }

void PropertyPass::onBinding(const Element &element, const QString &propertyName,
                             const QQmlJSMetaPropertyBinding &binding, const Element &bindingScope,
                             const Element &value)
{
    Q_UNUSED(element);
    Q_UNUSED(propertyName);
    Q_UNUSED(binding);
    Q_UNUSED(bindingScope);
    Q_UNUSED(value);
}

void PropertyPass::onRead(const Element &element, const QString &propertyName,
                          const Element &readScope, QQmlJS::SourceLocation location)
{
    Q_UNUSED(element);
    Q_UNUSED(propertyName);
    Q_UNUSED(readScope);
    Q_UNUSED(location);
}

void PropertyPass::onWrite(const Element &element, const QString &propertyName,
                           const Element &value, const Element &writeScope,
                           QQmlJS::SourceLocation location)
{
    Q_UNUSED(element);
    Q_UNUSED(propertyName);
    Q_UNUSED(writeScope);
    Q_UNUSED(value);
    Q_UNUSED(location);
}

DebugPropertyPass::DebugPropertyPass(QQmlSA::PassManager *manager) : QQmlSA::PropertyPass(manager)
{
}

void DebugPropertyPass::onRead(const QQmlSA::Element &element, const QString &propertyName,
                               const QQmlSA::Element &readScope, QQmlJS::SourceLocation location)
{
    emitWarning(u"onRead "_s
                        + (element->internalName().isEmpty() ? element->baseTypeName()
                                                             : element->internalName())
                        + u' ' + propertyName + u' ' + readScope->internalName() + u' '
                        + QString::number(location.startLine) + u':'
                        + QString::number(location.startColumn),
                qmlPlugin, location);
}

void DebugPropertyPass::onBinding(const QQmlSA::Element &element, const QString &propertyName,
                                  const QQmlJSMetaPropertyBinding &binding,
                                  const QQmlSA::Element &bindingScope, const QQmlSA::Element &value)
{
    const auto location = binding.sourceLocation();
    emitWarning(u"onBinding element: '"_s
                        + (element->internalName().isEmpty() ? element->baseTypeName()
                                                             : element->internalName())
                        + u"' property: '"_s + propertyName + u"' value: '"_s
                        + (value.isNull()
                                   ? u"NULL"_s
                                   : (value->internalName().isNull() ? value->baseTypeName()
                                                                     : value->internalName()))
                        + u"' binding_scope: '"_s
                        + (bindingScope->internalName().isEmpty() ? bindingScope->baseTypeName()
                                                                  : bindingScope->internalName())
                        + u"' "_s + QString::number(location.startLine) + u':'
                        + QString::number(location.startColumn),
                qmlPlugin, location);
}

void DebugPropertyPass::onWrite(const QQmlSA::Element &element, const QString &propertyName,
                                const QQmlSA::Element &value, const QQmlSA::Element &writeScope,
                                QQmlJS::SourceLocation location)
{
    emitWarning(u"onWrite "_s + element->baseTypeName() + u' ' + propertyName + u' '
                        + value->internalName() + u' ' + writeScope->internalName() + u' '
                        + QString::number(location.startLine) + u':'
                        + QString::number(location.startColumn),
                qmlPlugin, location);
}
}

QT_END_NAMESPACE