aboutsummaryrefslogtreecommitdiffstats
path: root/src/qmlcompiler/qqmljsfunctioninitializer.cpp
blob: 09928364b19fbae05e2d395d4876f30a83cfff04 (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
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "qqmljsfunctioninitializer_p.h"

#include <private/qqmljsmemorypool_p.h>

#include <QtCore/qloggingcategory.h>
#include <QtCore/qfileinfo.h>

#include <QtQml/private/qqmlsignalnames_p.h>

QT_BEGIN_NAMESPACE

using namespace Qt::StringLiterals;

/*!
 * \internal
 * \class QQmlJSFunctionInitializer
 *
 * QQmlJSFunctionInitializer analyzes the IR to produce an initial
 * QQmlJSCompilePass::Function for further analysis. It only looks for the
 * signature and the QML scope and doesn't visit the byte code.
 */

static QString bindingTypeDescription(QmlIR::Binding::Type type)
{
    switch (type) {
    case QmlIR::Binding::Type_Invalid:
        return u"invalid"_s;
    case QmlIR::Binding::Type_Boolean:
        return u"a boolean"_s;
    case QmlIR::Binding::Type_Number:
        return u"a number"_s;
    case QmlIR::Binding::Type_String:
        return u"a string"_s;
    case QmlIR::Binding::Type_Null:
        return u"null"_s;
    case QmlIR::Binding::Type_Translation:
        return u"a translation"_s;
    case QmlIR::Binding::Type_TranslationById:
        return u"a translation by id"_s;
    case QmlIR::Binding::Type_Script:
        return u"a script"_s;
    case QmlIR::Binding::Type_Object:
        return u"an object"_s;
    case QmlIR::Binding::Type_AttachedProperty:
        return u"an attached property"_s;
    case QmlIR::Binding::Type_GroupProperty:
        return u"a grouped property"_s;
    }

    return u"nothing"_s;
}

void QQmlJSFunctionInitializer::populateSignature(
        const QV4::Compiler::Context *context, QQmlJS::AST::FunctionExpression *ast,
        QQmlJSCompilePass::Function *function, QQmlJS::DiagnosticMessage *error)
{
    const auto signatureError = [&](const QString &message) {
        error->type = QtWarningMsg;
        error->loc = ast->firstSourceLocation();
        error->message = message;
        function->isFullyTyped = false;
    };

    if (!m_typeResolver->canCallJSFunctions()) {
        signatureError(u"Ignoring type annotations as requested "
                       "by pragma FunctionSignatureBehavior"_s);
        return;
    }

    QQmlJS::AST::BoundNames arguments;
    if (ast->formals)
        arguments = ast->formals->formals();

    // If the function has no arguments and no return type annotation we assume it's untyped.
    // You can annotate it to return void to make it typed.
    // Otherwise we first assume it's typed and reset the flag if we detect a problem.
    function->isFullyTyped = !arguments.isEmpty() || ast->typeAnnotation;

    if (function->argumentTypes.isEmpty()) {
        for (const QQmlJS::AST::BoundName &argument : std::as_const(arguments)) {
            if (argument.typeAnnotation) {
                if (const auto type = m_typeResolver->typeFromAST(argument.typeAnnotation->type)) {
                    function->argumentTypes.append(
                                m_typeResolver->tracked(
                                    m_typeResolver->globalType(type)));
                } else {
                    function->argumentTypes.append(
                                m_typeResolver->tracked(
                                    m_typeResolver->globalType(m_typeResolver->varType())));
                    signatureError(u"Cannot resolve the argument type %1."_s
                                   .arg(argument.typeAnnotation->type->toString()));
                }
            } else {
                function->argumentTypes.append(
                            m_typeResolver->tracked(
                                m_typeResolver->globalType(m_typeResolver->varType())));
                signatureError(u"Functions without type annotations won't be compiled"_s);
            }
        }
    } else {
        for (qsizetype i = 0, end = arguments.size(); i != end; ++i) {
            const QQmlJS::AST::BoundName &argument = arguments[i];
            if (argument.typeAnnotation) {
                if (const auto type = m_typeResolver->typeFromAST(argument.typeAnnotation->type)) {
                    if (!m_typeResolver->registerContains(function->argumentTypes[i], type)) {
                        signatureError(u"Type annotation %1 on signal handler "
                                        "contradicts signal argument type %2"_s
                                       .arg(argument.typeAnnotation->type->toString(),
                                            function->argumentTypes[i].descriptiveName()));
                    }
                }
            }
        }
    }

    if (!function->returnType.isValid()) {
        if (ast->typeAnnotation) {
            function->returnType = m_typeResolver->globalType(
                    m_typeResolver->typeFromAST(ast->typeAnnotation->type));
            if (!function->returnType.isValid())
                signatureError(u"Cannot resolve return type %1"_s.arg(
                                   QmlIR::IRBuilder::asString(ast->typeAnnotation->type->typeId)));
        }
    }

    for (int i = QQmlJSCompilePass::FirstArgument + function->argumentTypes.size();
         i < context->registerCountInFunction; ++i) {
        function->registerTypes.append(m_typeResolver->tracked(
                                           m_typeResolver->globalType(m_typeResolver->voidType())));
    }

    function->addressableScopes = m_typeResolver->objectsById();
    function->code = context->code;
    function->sourceLocations = context->sourceLocationTable.get();
}

static void diagnose(
        const QString &message, QtMsgType type, const QQmlJS::SourceLocation &location,
        QQmlJS::DiagnosticMessage *error)
{
    *error = QQmlJS::DiagnosticMessage{
        message,
        type,
        location
    };
}

QQmlJSCompilePass::Function QQmlJSFunctionInitializer::run(
        const QV4::Compiler::Context *context,
        const QString &propertyName,
        QQmlJS::AST::Node *astNode,
        const QmlIR::Binding &irBinding,
        QQmlJS::DiagnosticMessage *error)
{
    QQmlJS::SourceLocation bindingLocation;
    bindingLocation.startLine = irBinding.location.line();
    bindingLocation.startColumn = irBinding.location.column();

    QQmlJSCompilePass::Function function;
    function.qmlScope = m_scopeType;

    if (irBinding.type() != QmlIR::Binding::Type_Script) {
        diagnose(u"Binding is not a script binding, but %1."_s.arg(
                     bindingTypeDescription(QmlIR::Binding::Type(quint32(irBinding.type())))),
                 QtDebugMsg, bindingLocation, error);
    }

    function.isProperty = m_objectType->hasProperty(propertyName);
    if (!function.isProperty) {
        if (QQmlSignalNames::isHandlerName(propertyName)) {
            if (auto actualPropertyName =
                QQmlSignalNames::changedHandlerNameToPropertyName(propertyName);
                actualPropertyName && m_objectType->hasProperty(*actualPropertyName)) {
                function.isSignalHandler = true;
            } else {
                auto signalName = QQmlSignalNames::handlerNameToSignalName(propertyName);
                const auto methods = m_objectType->methods(*signalName);
                for (const auto &method : methods) {
                    if (method.isCloned())
                        continue;
                    if (method.methodType() == QQmlJSMetaMethodType::Signal) {
                        function.isSignalHandler = true;
                        const auto arguments = method.parameters();
                        for (qsizetype i = 0, end = arguments.size(); i < end; ++i) {
                            const auto &type = arguments[i].type();
                            if (type.isNull()) {
                                diagnose(u"Cannot resolve the argument type %1."_s.arg(
                                                 arguments[i].typeName()),
                                         QtDebugMsg, bindingLocation, error);
                                function.argumentTypes.append(
                                        m_typeResolver->tracked(
                                                m_typeResolver->globalType(m_typeResolver->varType())));
                            } else {
                                function.argumentTypes.append(m_typeResolver->tracked(
                                        m_typeResolver->globalType(type)));
                            }
                        }
                        break;
                    }
                }
                if (!function.isSignalHandler) {
                    diagnose(u"Could not compile signal handler for %1: The signal does not exist"_s.arg(
                                     *signalName),
                             QtWarningMsg, bindingLocation, error);
                }
            }
        }
    }

    if (!function.isSignalHandler) {
        if (!function.isProperty) {
            diagnose(u"Could not compile binding for %1: The property does not exist"_s.arg(
                         propertyName),
                     QtWarningMsg, bindingLocation, error);
        }

        const auto property = m_objectType->property(propertyName);
        if (const QQmlJSScope::ConstPtr propertyType = property.type()) {
            function.returnType = m_typeResolver->globalType(propertyType->isListProperty()
                ? m_typeResolver->qObjectListType()
                : QQmlJSScope::ConstPtr(property.type()));
        } else {
            QString message = u"Cannot resolve property type %1 for binding on %2."_s
                    .arg(property.typeName(), propertyName);
            if (m_objectType->isNameDeferred(propertyName)) {
                // If the property doesn't exist but the name is deferred, then
                // it's deferred via the presence of immediate names. Those are
                // most commonly used to enable generalized grouped properties.
                message += u" You may want use ID-based grouped properties here.";
            }
            diagnose(message, QtWarningMsg, bindingLocation, error);
        }

        if (!property.bindable().isEmpty() && !property.isPrivate())
            function.isQPropertyBinding = true;
    }

    QQmlJS::MemoryPool pool;
    auto ast = astNode->asFunctionDefinition();
    if (!ast) {
        QQmlJS::AST::Statement *stmt = astNode->statementCast();
        if (!stmt) {
            Q_ASSERT(astNode->expressionCast());
            QQmlJS::AST::ExpressionNode *expr = astNode->expressionCast();
            stmt = new (&pool) QQmlJS::AST::ExpressionStatement(expr);
        }
        auto body = new (&pool) QQmlJS::AST::StatementList(stmt);
        body = body->finish();

        QString name = u"binding for "_s; // ####
        ast = new (&pool) QQmlJS::AST::FunctionDeclaration(
                pool.newString(name), /*formals*/ nullptr, body);
        ast->lbraceToken = astNode->firstSourceLocation();
        ast->functionToken = ast->lbraceToken;
        ast->rbraceToken = astNode->lastSourceLocation();
    }

    populateSignature(context, ast, &function, error);
    return function;
}

QQmlJSCompilePass::Function QQmlJSFunctionInitializer::run(
        const QV4::Compiler::Context *context,
        const QString &functionName, QQmlJS::AST::Node *astNode,
        QQmlJS::DiagnosticMessage *error)
{
    Q_UNUSED(functionName);

    QQmlJSCompilePass::Function function;
    function.qmlScope = m_scopeType;

    auto ast = astNode->asFunctionDefinition();
    Q_ASSERT(ast);

    populateSignature(context, ast, &function, error);
    return function;
}

QT_END_NAMESPACE