aboutsummaryrefslogtreecommitdiffstats
path: root/tools/qmljsrootgen/main.cpp
blob: c721d7996469667f00304a078bba574f20d1b600 (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
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
/****************************************************************************
**
** Copyright (C) 2021 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtQml/private/qjsvalue_p.h>
#include <QtQml/private/qv4propertykey_p.h>
#include <QtQml/private/qv4global_p.h>
#include <QtQml/private/qv4functionobject_p.h>
#include <QtQml/qjsengine.h>
#include <QtQml/qjsmanagedvalue.h>

#include <QtCore/qcoreapplication.h>
#include <QtCore/qfile.h>

#include <QtCore/qjsondocument.h>
#include <QtCore/qjsonarray.h>
#include <QtCore/qjsonobject.h>

struct PropertyInfo
{
    QString name;
    bool writable;
};

static QV4::ReturnedValue asManaged(const QJSManagedValue &value)
{
    const QJSValue jsVal = value.toJSValue();
    const QV4::Managed *managed = QJSValuePrivate::asManagedType<QV4::Managed>(&jsVal);
    return managed ? managed->asReturnedValue() : QV4::Encode::undefined();
}

static QJSManagedValue checkedProperty(const QJSManagedValue &value, const QString &name)
{
    return value.hasProperty(name) ? QJSManagedValue(value.property(name), value.engine())
                                   : QJSManagedValue(QJSPrimitiveUndefined(), value.engine());
}

QList<PropertyInfo> getPropertyInfos(const QJSManagedValue &value)
{
    QV4::Scope scope(value.engine()->handle());
    QV4::ScopedObject scoped(scope, asManaged(value));
    if (!scoped)
        return {};

    QList<PropertyInfo> infos;

    QScopedPointer<QV4::OwnPropertyKeyIterator> iterator(scoped->ownPropertyKeys(scoped));
    QV4::Scoped<QV4::InternalClass> internalClass(scope, scoped->internalClass());

    for (auto key = iterator->next(scoped); key.isValid(); key = iterator->next(scoped)) {
        if (key.isSymbol())
            continue;

        const auto *entry = internalClass->d()->propertyTable.lookup(key);
        infos.append({
            key.toQString(),
            !entry || internalClass->d()->propertyData.at(entry->index).isWritable()
        });
    };

    return infos;
}

struct State {
    QMap<QString, QJSValue> constructors;
    QMap<QString, QJSValue> prototypes;
    QSet<QString> primitives;
};

static QString buildConstructor(const QJSManagedValue &constructor, QJsonArray *classes,
                                State *seen, const QString &name);

static QString findClassName(const QJSManagedValue &value)
{
    if (value.isUndefined())
        return QStringLiteral("undefined");
    if (value.isBoolean())
        return QStringLiteral("boolean");
    if (value.isNumber())
        return QStringLiteral("number");
    if (value.isString())
        return QStringLiteral("string");
    if (value.isSymbol())
        return QStringLiteral("symbol");

    QV4::Scope scope(value.engine()->handle());
    if (QV4::ScopedValue scoped(scope, asManaged(value)); scoped->isManaged())
        return scoped->managed()->vtable()->className;

    Q_UNREACHABLE();
    return QString();
}

static QString buildClass(const QJSManagedValue &value, QJsonArray *classes,
                          State *seen, const QString &name)
{
    if (value.isNull())
        return QString();

    if (seen->primitives.contains(name))
        return name;
    else if (name.at(0).isLower())
        seen->primitives.insert(name);

    QJsonObject classObject;
    QV4::Scope scope(value.engine()->handle());

    classObject[QStringLiteral("className")] = name;
    classObject[QStringLiteral("qualifiedClassName")] = name;

    classObject[QStringLiteral("classInfos")] = QJsonArray({
                                                          QJsonObject({
                                                              { QStringLiteral("name"), QStringLiteral("QML.Element") },
                                                              { QStringLiteral("value"), QStringLiteral("anonymous") }
                                                          })
                                                      });

    if (value.isObject() || value.isFunction())
        classObject[QStringLiteral("object")] = true;
    else
        classObject[QStringLiteral("gadget")] = true;

    const QJSManagedValue prototype = value.prototype();

    if (!prototype.isNull()) {
        QString protoName;
        for (auto it = seen->prototypes.begin(), end = seen->prototypes.end(); it != end; ++it) {
            if (prototype.strictlyEquals(QJSManagedValue(*it, value.engine()))) {
                protoName = it.key();
                break;
            }
        }

        if (protoName.isEmpty()) {
            if (name.endsWith(QStringLiteral("ErrorPrototype"))
                    && name != QStringLiteral("ErrorPrototype")) {
                protoName = QStringLiteral("ErrorPrototype");
            } else if (name.endsWith(QStringLiteral("Prototype"))) {
                protoName = findClassName(prototype);
                if (!protoName.endsWith(QStringLiteral("Prototype")))
                    protoName += QStringLiteral("Prototype");
            } else {
                protoName = name.at(0).toUpper() + name.mid(1) + QStringLiteral("Prototype");
            }

            auto it = seen->prototypes.find(protoName);
            if (it == seen->prototypes.end()) {
                seen->prototypes.insert(protoName, prototype.toJSValue());
                buildClass(prototype, classes, seen, protoName);
            } else if (!it->strictlyEquals(prototype.toJSValue())) {
                qWarning() << "Cannot find a distinct name for the prototype of" << name;
                qWarning() << protoName << "is already in use.";
            }
        }

        classObject[QStringLiteral("superClasses")] = QJsonArray {
                QJsonObject ({
                                 { QStringLiteral("access"), QStringLiteral("public") },
                                 { QStringLiteral("name"), protoName }
                             })};
    }

    QJsonArray properties, methods;

    for (const PropertyInfo &info : getPropertyInfos(value)) {
        QJSManagedValue prop = checkedProperty(value, info.name);
        if (prop.engine()->hasError()) {
            qWarning() << "Cannot retrieve property " << info.name << "of" << name;
            qWarning().noquote() << "    " << prop.engine()->catchError().toString();
        }

        // Method or constructor
        if (prop.isFunction()) {
            QV4::Scoped<QV4::FunctionObject> propFunction(scope, asManaged(prop));

            QJsonObject methodObject;

            methodObject.insert(QStringLiteral("access"), QStringLiteral("public"));
            methodObject.insert(QStringLiteral("name"), info.name);

            if (propFunction->isConstructor()) {
                methodObject.insert(QStringLiteral("isConstructor"), true);

                QString ctorName;
                if (info.name.at(0).isUpper()) {
                    ctorName = info.name;
                } else if (info.name == QStringLiteral("constructor")) {
                    if (name.endsWith(QStringLiteral("Prototype")))
                        ctorName = name.chopped(strlen("Prototype"));
                    else if (name.endsWith(QStringLiteral("PrototypeMember")))
                        ctorName = name.chopped(strlen("PrototypeMember"));
                    else
                        ctorName = name;

                    if (!ctorName.endsWith(QStringLiteral("Constructor")))
                        ctorName += QStringLiteral("Constructor");
                }

                methodObject.insert(
                            QStringLiteral("returnType"),
                            buildConstructor(prop, classes, seen, ctorName));
            }

            const int formalParams = propFunction->getLength();

            QJsonArray arguments;
            for (int i = 0; i < formalParams; i++)
                arguments.append(QJsonObject {});

            methodObject.insert(QStringLiteral("arguments"), arguments);

            methods.append(methodObject);

            continue;
        }

        // ...else it's just a property
        QJsonObject propertyObject;

        propertyObject.insert(QStringLiteral("name"), info.name);

        // Insert faux member entry if we're allowed to write to this
        if (info.writable)
            propertyObject.insert(QStringLiteral("member"), QStringLiteral("fakeMember"));

        if (!prop.isUndefined() && !prop.isNull()) {
            QString propClassName = findClassName(prop);
            if (!propClassName.at(0).isLower() && info.name != QStringLiteral("prototype")) {
                propClassName = (name == QStringLiteral("GlobalObject"))
                        ? QString()
                        : name.at(0).toUpper() + name.mid(1);

                propClassName += info.name.at(0).toUpper() + info.name.mid(1);
                propertyObject.insert(QStringLiteral("type"),
                                      buildClass(prop, classes, seen, propClassName));
            } else {
                // If it's the "prototype" property we just refer to generic "Object",
                // and if it's a value type, we handle it separately.
                propertyObject.insert(QStringLiteral("type"), propClassName);
            }
        }
        properties.append(propertyObject);
    }

    classObject[QStringLiteral("properties")] = properties;
    classObject[QStringLiteral("methods")] = methods;

    classes->append(classObject);

    return name;
}

static QString buildConstructor(const QJSManagedValue &constructor, QJsonArray *classes,
                                State *seen, const QString &name)
{
    QJSEngine *engine = constructor.engine();

    // If the constructor appears in the global object, use the name from there.
    const QJSManagedValue globalObject(engine->globalObject(), engine);
    const auto infos = getPropertyInfos(globalObject);
    for (const auto &info : infos) {
        const QJSManagedValue member(globalObject.property(info.name), engine);
        if (member.strictlyEquals(constructor) && info.name != name)
            return buildConstructor(constructor, classes, seen, info.name);
    }

    QJSManagedValue constructed;
    if (name == QStringLiteral("Symbol"))
        return QStringLiteral("undefined"); // Cannot construct symbols with "new";

    if (name == QStringLiteral("URL")) {
        constructed = QJSManagedValue(
                    constructor.callAsConstructor({ QJSValue(QStringLiteral("http://a.bc")) }),
                    engine);
    } else if (name == QStringLiteral("Promise")) {
        constructed = QJSManagedValue(
                    constructor.callAsConstructor(
                        { engine->evaluate(QStringLiteral("(function() {})")) }),
                        engine);
    } else if (name == QStringLiteral("DataView")) {
        constructed = QJSManagedValue(
                    constructor.callAsConstructor(
                        { engine->evaluate(QStringLiteral("new ArrayBuffer()")) }),
                        engine);
    } else if (name == QStringLiteral("Proxy")) {
        constructed = QJSManagedValue(constructor.callAsConstructor(
                                          { engine->newObject(), engine->newObject() }), engine);
    } else {
        constructed = QJSManagedValue(constructor.callAsConstructor(), engine);
    }

    if (engine->hasError()) {
        qWarning() << "Calling constructor" << name << "failed";
        qWarning().noquote() << "    " << engine->catchError().toString();
        return QString();
    } else if (name.isEmpty()) {
        Q_UNREACHABLE();
    }

    auto it = seen->constructors.find(name);
    if (it == seen->constructors.end()) {
        seen->constructors.insert(name, constructor.toJSValue());
        return buildClass(constructed, classes, seen, name);
    } else if (!constructor.strictlyEquals(QJSManagedValue(*it, constructor.engine()))) {
        qWarning() << "Two constructors of the same name seen:" << name;
    }
    return name;
}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QCoreApplication::setApplicationVersion(QLatin1String(QT_VERSION_STR));

    QStringList args = app.arguments();

    if (args.length() != 2) {
        qWarning().noquote() << app.applicationName() << "[output json path]";
        return 1;
    }

    QString fileName = args.at(1);

    QJSEngine engine;
    engine.installExtensions(QJSEngine::AllExtensions);

    QJsonArray classesArray;
    State seen;

    // object. Do this first to claim the "Object" name for the prototype.
    buildClass(QJSManagedValue(engine.newObject(), &engine), &classesArray, &seen,
               QStringLiteral("object"));


    buildClass(QJSManagedValue(engine.globalObject(), &engine), &classesArray, &seen,
               QStringLiteral("GlobalObject"));

    // Add JS types, in case they aren't used anywhere.


    // function
    buildClass(QJSManagedValue(engine.evaluate(QStringLiteral("(function() {})")), &engine),
               &classesArray, &seen, QStringLiteral("function"));

    // string
    buildClass(QJSManagedValue(QStringLiteral("s"), &engine), &classesArray, &seen,
               QStringLiteral("string"));

    // undefined
    buildClass(QJSManagedValue(QJSPrimitiveUndefined(), &engine), &classesArray, &seen,
               QStringLiteral("undefined"));

    // number
    buildClass(QJSManagedValue(QJSPrimitiveValue(1.1), &engine), &classesArray, &seen,
               QStringLiteral("number"));

    // boolean
    buildClass(QJSManagedValue(QJSPrimitiveValue(true), &engine), &classesArray, &seen,
               QStringLiteral("boolean"));

    // symbol
    buildClass(QJSManagedValue(engine.newSymbol(QStringLiteral("s")), &engine),
               &classesArray, &seen, QStringLiteral("symbol"));

    // Generate the fake metatypes json structure
    QJsonDocument metatypesJson = QJsonDocument(
                QJsonArray({
                               QJsonObject({
                                   {QStringLiteral("classes"), classesArray}
                               })
                           })
                );

    QFile file(fileName);
    if (!file.open(QFile::WriteOnly)) {
        qWarning() << "Failed to write metatypes json to" << fileName;
        return 1;
    }

    file.write(metatypesJson.toJson());
    file.close();

    return 0;
}