aboutsummaryrefslogtreecommitdiffstats
path: root/src/qml/jsruntime/qv4function.cpp
blob: ae36b563e0c0f7b62ca4baaa9f4ec45f5bfb0a82 (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
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qml/qqmlprivate.h"
#include "qv4function_p.h"
#include "qv4managed_p.h"
#include "qv4string_p.h"
#include "qv4value_p.h"
#include "qv4engine_p.h"
#include <private/qv4mm_p.h>
#include <private/qv4identifiertable_p.h>
#include <private/qv4functiontable_p.h>
#include <assembler/MacroAssemblerCodeRef.h>
#include <private/qv4vme_moth_p.h>
#include <private/qqmlglobal_p.h>
#include <private/qv4jscall_p.h>
#include <private/qqmlpropertycachecreator_p.h>

QT_BEGIN_NAMESPACE

namespace QV4 {

bool Function::call(QObject *thisObject, void **a, const QMetaType *types, int argc,
                    ExecutionContext *context)
{
    if (kind != AotCompiled) {
        return QV4::convertAndCall(
                    context->engine(), thisObject, a, types, argc,
                    [this, context](const Value *thisObject, const Value *argv, int argc) {
            return call(thisObject, argv, argc, context);
        });
    }

    ExecutionEngine *engine = context->engine();
    MetaTypesStackFrame frame;
    frame.init(this, thisObject, context, a, types, argc);
    frame.push(engine);
    Moth::VME::exec(&frame, engine);
    frame.pop(engine);
    return !frame.isReturnValueUndefined();
}

static ReturnedValue doCall(
        QV4::Function *self, const QV4::Value *thisObject, const QV4::Value *argv, int argc,
        QV4::ExecutionContext *context)
{
    ExecutionEngine *engine = context->engine();
    JSTypesStackFrame frame;
    frame.init(self, argv, argc);
    frame.setupJSFrame(engine->jsStackTop, Value::undefinedValue(), context->d(),
                       thisObject ? *thisObject : Value::undefinedValue());
    engine->jsStackTop += frame.requiredJSStackFrameSize();
    frame.push(engine);
    ReturnedValue result = Moth::VME::exec(&frame, engine);
    frame.pop(engine);
    return result;
}

ReturnedValue Function::call(
        const Value *thisObject, const Value *argv, int argc, ExecutionContext *context) {
    switch (kind) {
    case AotCompiled:
        return QV4::convertAndCall(
                    context->engine(), &aotCompiledFunction, thisObject, argv, argc,
                    [this, context](
                        QObject *thisObject, void **a, const QMetaType *types, int argc) {
            call(thisObject, a, types, argc, context);
        });
    case JsTyped:
        return QV4::coerceAndCall(
                    context->engine(), &jsTypedFunction, compiledFunction, argv, argc,
                    [this, context, thisObject](const Value *argv, int argc) {
            return doCall(this, thisObject, argv, argc, context);
        });
    default:
        break;
    }

    return doCall(this, thisObject, argv, argc, context);
}

Function *Function::create(ExecutionEngine *engine, ExecutableCompilationUnit *unit,
                           const CompiledData::Function *function,
                           const QQmlPrivate::AOTCompiledFunction *aotFunction)
{
    return new Function(engine, unit, function, aotFunction);
}

void Function::destroy()
{
    delete this;
}

void Function::mark(MarkStack *ms)
{
    if (internalClass)
        internalClass->mark(ms);
}

static bool isSpecificType(const CompiledData::ParameterType &type)
{
    return type.typeNameIndexOrCommonType()
           != (type.indexIsCommonType() ? quint32(CompiledData::CommonType::Invalid) : 0);
}

Function::Function(ExecutionEngine *engine, ExecutableCompilationUnit *unit,
                   const CompiledData::Function *function,
                   const QQmlPrivate::AOTCompiledFunction *aotFunction)
    : FunctionData(engine, unit)
    , compiledFunction(function)
    , codeData(function->code())
{
    Scope scope(engine);
    Scoped<InternalClass> ic(scope, engine->internalClasses(EngineBase::Class_CallContext));

    // first locals
    const quint32_le *localsIndices = compiledFunction->localsTable();
    for (quint32 i = 0; i < compiledFunction->nLocals; ++i)
        ic = ic->addMember(engine->identifierTable->asPropertyKey(compilationUnit->runtimeStrings[localsIndices[i]]), Attr_NotConfigurable);

    const CompiledData::Parameter *formalsIndices = compiledFunction->formalsTable();
    bool enforceJsTypes = !unit->ignoresFunctionSignature();

    for (quint32 i = 0; i < compiledFunction->nFormals; ++i) {
        ic = ic->addMember(engine->identifierTable->asPropertyKey(compilationUnit->runtimeStrings[formalsIndices[i].nameIndex]), Attr_NotConfigurable);
        if (enforceJsTypes && !isSpecificType(formalsIndices[i].type))
            enforceJsTypes = false;
    }
    internalClass.set(engine, ic->d());

    nFormals = compiledFunction->nFormals;

    if (!enforceJsTypes)
        return;

    if (aotFunction) {
        aotCompiledCode = aotFunction->functionPtr;
        new (&aotCompiledFunction) AOTCompiledFunction;
        kind = AotCompiled;
        aotCompiledFunction.types.resize(aotFunction->numArguments + 1);
        aotFunction->signature(unit, aotCompiledFunction.types.data());
        return;
    }

    // If a function has any typed arguments, but an untyped return value, the return value is void.
    // If it doesn't have any arguments at all and the return value is untyped, the function is
    // untyped. Users can specifically set the return type to "void" to have it enforced.
    if (nFormals == 0 && !isSpecificType(compiledFunction->returnType))
        return;

    QQmlTypeLoader *typeLoader = engine->typeLoader();

    auto findQmlType = [&](const CompiledData::ParameterType &param) {
        const quint32 type = param.typeNameIndexOrCommonType();
        if (param.indexIsCommonType()) {
            return QQmlMetaType::qmlType(QQmlPropertyCacheCreatorBase::metaTypeForPropertyType(
                QV4::CompiledData::CommonType(type)));
        }

        if (type == 0 || !typeLoader)
            return QQmlType();

        const auto &base = unit->baseCompilationUnit();
        const QQmlType qmltype = QQmlTypePrivate::compositeQmlType(
                base, typeLoader, base->stringAt(type));
        return qmltype.typeId().isValid() ? qmltype : QQmlType();
    };

    new (&jsTypedFunction) JSTypedFunction;
    kind = JsTyped;
    jsTypedFunction.types.reserve(nFormals + 1);
    jsTypedFunction.types.append(findQmlType(compiledFunction->returnType));
    for (quint16 i = 0; i < nFormals; ++i)
        jsTypedFunction.types.append(findQmlType(formalsIndices[i].type));
}

Function::~Function()
{
    if (codeRef) {
        destroyFunctionTable(this, codeRef);
        delete codeRef;
    }

    switch (kind) {
    case JsTyped:
        jsTypedFunction.~JSTypedFunction();
        break;
    case AotCompiled:
        aotCompiledFunction.~AOTCompiledFunction();
        break;
    case JsUntyped:
    case Eval:
        break;
    }
}

void Function::updateInternalClass(ExecutionEngine *engine, const QList<QByteArray> &parameters)
{
    QStringList parameterNames;

    // Resolve duplicate parameter names:
    for (int i = 0, ei = parameters.size(); i != ei; ++i) {
        const QByteArray &param = parameters.at(i);
        int duplicate = -1;

        for (int j = i - 1; j >= 0; --j) {
            const QByteArray &prevParam = parameters.at(j);
            if (param == prevParam) {
                duplicate = j;
                break;
            }
        }

        if (duplicate == -1) {
            parameterNames.append(QString::fromUtf8(param));
        } else {
            const QString dup = parameterNames[duplicate];
            parameterNames.append(dup);
            parameterNames[duplicate] =
                    QString(QChar(0xfffe)) + QString::number(duplicate) + dup;
        }

    }

    Scope scope(engine);
    Scoped<InternalClass> ic(scope, engine->internalClasses(EngineBase::Class_CallContext));

    // first locals
    const quint32_le *localsIndices = compiledFunction->localsTable();
    for (quint32 i = 0; i < compiledFunction->nLocals; ++i) {
        ic = ic->addMember(
                engine->identifierTable->asPropertyKey(compilationUnit->runtimeStrings[localsIndices[i]]),
                Attr_NotConfigurable);
    }

    ScopedString arg(scope);
    for (const QString &parameterName : parameterNames) {
        arg = engine->newIdentifier(parameterName);
        ic = ic->addMember(arg->propertyKey(), Attr_NotConfigurable);
    }
    internalClass.set(engine, ic->d());
    nFormals = parameters.size();
}

QString Function::prettyName(const Function *function, const void *code)
{
    QString prettyName = function ? function->name()->toQString() : QString();
    if (prettyName.isEmpty()) {
        prettyName = QString::number(reinterpret_cast<quintptr>(code), 16);
        prettyName.prepend(QLatin1String("QV4::Function(0x"));
        prettyName.append(QLatin1Char(')'));
    }
    return prettyName;
}

QQmlSourceLocation Function::sourceLocation() const
{
    return QQmlSourceLocation(
            sourceFile(), compiledFunction->location.line(), compiledFunction->location.column());
}

FunctionData::FunctionData(EngineBase *engine, ExecutableCompilationUnit *compilationUnit_)
{
    compilationUnit.set(engine, compilationUnit_);
}

} // namespace QV4

QT_END_NAMESPACE